// Update is called once per frame void Update() { if (time_since_last_attack >= AttackCooldown && !attacking && !status.ControlsAreLocked) { GameObject target = null; var cols = Physics2D.OverlapCircleAll(transform.position, AttackRange); foreach (Collider2D col in cols) { if (col.gameObject.CompareTag("Player") && Vector3.Distance(col.transform.position, transform.position) > AttackMinSeperation) { if (!target) { target = col.gameObject; } else { float dist = Vector3.Distance(transform.position, target.transform.position); dist -= (transform.position - col.transform.position).magnitude; target = dist > 0 ? target : col.gameObject; } } } if (target) { attacking = true; StartCoroutine(PrepareAttack(VUtils.Vec3ToVec2(target.transform.position - transform.position).normalized)); } } else { time_since_last_attack += TimeManager.deltaTime; } }
Vector3 ObstacleAvoidance() { Vector2[] directions = { Vector2.up, Vector2.right, Vector2.down, Vector2.left }; Vector2 steering = Vector3.zero; int total = 0; Vector2 future_pos; foreach (Vector2 dir in directions) { future_pos = VUtils.Vec3ToVec2(transform.position) + dir; if (Physics2D.OverlapPoint(future_pos, LayerMask.GetMask("Impassables", "Hazards"))) { steering -= dir; total++; } } future_pos = VUtils.Vec3ToVec2(transform.position) + rb.velocity.normalized; if (Physics2D.OverlapPoint(future_pos, LayerMask.GetMask("Impassables", "Hazards"))) { steering -= rb.velocity.normalized; total++; } if (total > 0) { steering /= total; } return(VUtils.Vec2ToVec3(steering).normalized); }
Vector3 Cohesion() { Vector3 steering = Vector3.zero; int total = 0; foreach (Collider2D col in Physics2D.OverlapCircleAll(VUtils.Vec3ToVec2(transform.position), SeperationRadius)) { if (col.gameObject != gameObject) { AIBoids ai = col.gameObject.GetComponent <AIBoids>(); if (ai) { Vector3 line_to_other = col.transform.position - transform.position; steering += line_to_other; total++; } } } if (total > 0) { steering /= total; // steering -= VUtils.Vec2ToVec3(rb.velocity); // steering = Mathf.Min(steering, MaxForce); } return(steering.normalized); }
public void DrawNode(int freq) { Color c = Color.blue; int j = 0; foreach (KeyValuePair <Vector2, NavNode> entry in NodeDict) { if (j % freq == 0) { Vector3 pos = VUtils.Vec2ToVec3(entry.Key); Debug.DrawLine(pos, pos + Vector3.right * 0.1f, c, 20, false); // for (int i = 0; i < 8; ++i) // { // if (GetDir(entry.Value, i) != p_null) // { // Debug.DrawLine( // VUtils.Vec2ToVec3(entry.Key), // VUtils.Vec2ToVec3(GetDir(entry.Value, i)), // c, // 10, // false // ); // } // } } ++j; } }
public void Initialize() { levelTxt = RootSystem.cfg.level.GetComponent <Text>(); levelTxt.text = "Level: " + VUtils.getInstance().getLevel(); xpBar = RootSystem.cfg.xpBar.GetComponent <RectTransform>(); xpBar.sizeDelta = new Vector2(LevelLogic.getXPPercentage(game.experience) * 2, 22); }
void SetVelocity() { acceleration *= SlowingFactor; acceleration = acceleration.magnitude < 0.01f ? Vector3.zero : acceleration; if (target && Vector3.Distance(transform.position, target.position) < StoppingDistance && Vector3.Distance(transform.position, target.position) > StoppingDistance / 2) { rb.velocity = Vector2.zero; } else { if (target) { Vector3 target_dir = (target.position - transform.position).normalized; heading.SetHeading((Vector2)target_dir); acceleration += target_dir; acceleration += Seperation() * SeperationMultiplier; Debug.DrawRay(transform.position, Seperation(), Color.red, 0, false); acceleration += Cohesion() * CohesionMultiplier; acceleration += ObstacleAvoidance() * ObstacleAvoidanceStrength; if (acceleration.magnitude > MaxForce) { acceleration = acceleration.normalized * MaxForce; } Debug.DrawRay(transform.position, acceleration, Color.green, 0, false); } if (Vector3.Distance(transform.position, target.position) > StoppingDistance) { rb.velocity += VUtils.Vec3ToVec2(acceleration) * SteeringForce; } else { rb.velocity -= VUtils.Vec3ToVec2(acceleration) * SteeringForce; } rb.velocity = rb.velocity.magnitude > max_speed ? rb.velocity.normalized * max_speed : rb.velocity; rb.velocity = rb.velocity.magnitude < MinSpeed ? Vector2.zero : rb.velocity; } if (anim) { anim.SetFloat("Speed", rb.velocity.magnitude); } if (rb.velocity.x > 0) { transform.localScale = new Vector3(1, 1, 1); } else { transform.localScale = new Vector3(-1, 1, 1); } }
protected override IEnumerator AttackCoroutine(Vector2 direction) { int idx = Random.Range(0, 3); SoundManager.PlaySound(BigSounds[idx]); SoundManager.PlaySound(SoundManager.Sound.Fireball); Vector3 instantiation_point = transform.position + VUtils.Vec2ToVec3(direction).normalized *ProjectileLeeway; GameObject fireball = Instantiate(FireballProjectiles, instantiation_point, Quaternion.identity); Rigidbody2D rb = fireball.GetComponent <Rigidbody2D>(); rb.velocity = direction.normalized * ProjectileSpeed; yield return(null); }
public void Initialize() { var player = context.game.CreateEntity(); GameObject go = RootSystem.cfg.player; go.GetComponent <Animator>().Play("idle"); go.Link(player, context.game); player.AddView(go); player.isDead = false; player.AddSpeed(0); player.AddScore(VUtils.getInstance().getHighscore(), 0); player.AddExperience(VUtils.getInstance().getLevel(), VUtils.getInstance().getXP()); }
static IEnumerator ShakeScreenCoroutine(float duration, float intensity) { float timer = 0; // int num_shakes = 0; // float shake_freq = 0; while (timer < duration) { timer += TimeManager.deltaTime; main.follow_offset = VUtils.Vec2ToVec3(Random.insideUnitCircle * intensity); yield return(null); } main.follow_offset = Vector3.zero; }
Vector3 KeepInBounds(Vector3 new_position) { Vector3 clamped_position = new_position; if (new_position.y > transform.position.y) { Vector3 check_position = Camera.main.ViewportToWorldPoint(new Vector3(0.5f, 1, 0)); check_position.y -= Margin; if (!Physics2D.OverlapPoint(VUtils.Vec3ToVec2(check_position), LayerMask.GetMask("Nav"))) { clamped_position.y = transform.position.y; } } else { Vector3 check_position = Camera.main.ViewportToWorldPoint(new Vector3(0.5f, 0, 0)); check_position.y += Margin; if (!Physics2D.OverlapPoint(VUtils.Vec3ToVec2(check_position), LayerMask.GetMask("Nav"))) { clamped_position.y = transform.position.y; } } if (new_position.x > transform.position.x) { Vector3 check_position = Camera.main.ViewportToWorldPoint(new Vector3(1, 0.5f, 0)); check_position.x -= Margin; if (!Physics2D.OverlapPoint(VUtils.Vec3ToVec2(check_position), LayerMask.GetMask("Nav"))) { clamped_position.x = transform.position.x; } } else { Vector3 check_position = Camera.main.ViewportToWorldPoint(new Vector3(0, 0.5f, 0)); check_position.x += Margin; if (!Physics2D.OverlapPoint(VUtils.Vec3ToVec2(check_position), LayerMask.GetMask("Nav"))) { clamped_position.x = transform.position.x; } } return(clamped_position); }
void Spawn() { switch (toastText) { case 1: toast.ShowToast(("Grapple and throw enemies into the priests on the floating islands!", 6)); toastText = 0; break; case 2: toast.ShowToast(("Remember to drink mead with LB if you're running low on health! But beware -- it will slow movement!", 6)); toastText = 0; break; case 4: toast.ShowToast(("Grapple and throw enemies into the health crystals to stop Geminator from regenerating health!", 7)); toastText = 0; break; default: break; } float val = Random.Range(0f, total); GameObject spawn = enemies[0]; for (int i = 0; i < enemies.Length; i++) { if (val <= enemy_weights[i]) { spawn = enemies[i]; break; } else { val -= enemy_weights[i]; } } SoundManager.PlaySound(SoundManager.Sound.Fireball); Vector3 spawn_point = VUtils.Vec2ToVec3(Random.insideUnitCircle) * 2 + transform.position; Instantiate(SpawnEffect, spawn_point, Quaternion.identity); GameObject enemy = Instantiate(spawn, spawn_point, Quaternion.identity); enemy.transform.parent = transform; remainingEnemies++; counter = 0; }
public float GetSpeed() { Vector2 new_pos = VUtils.Vec3ToVec2(transform.position); if (new_pos != current_pos) { prev_pos = current_pos; prev_diff_pos = current_pos; current_pos = new_pos; } else { prev_diff_pos = current_pos; } return((current_pos - prev_diff_pos).magnitude); }
protected override void Execute(List <InputEntity> entities) { if (!RootSystem.cfg.isPaused) { Config cfg = RootSystem.cfg; cfg.player.GetComponent <Animator>().Play("fall"); RootSystem.cfg.isPaused = true; game.isDead = true; LevelLogic.addXP(game.score.currScore, game.experience); RootSystem.cfg.gameOverMenu.AddComponent <FadeIn>(); RootSystem.cfg.levelBar.AddComponent <FadeIn>(); if (game.score.currScore > game.score.highscore) { game.score.highscore = game.score.currScore; } VUtils.getInstance().save(game.experience.level, game.experience.xp, game.score.highscore); RootSystem.cfg.endScore.GetComponent <Text>().text = "highscore: " + game.score.highscore + "\n" + game.score.currScore; RootSystem.cfg.gamemenu.AddComponent <FadeOut>(); GameObject lowerPart = entities[0].playerCollision.other.transform.GetChild(0).gameObject; GameObject upperPart = entities[0].playerCollision.other.transform.GetChild(1).gameObject; Transform parent = lowerPart.transform.parent; upperPart.transform.parent = parent.parent; lowerPart.transform.parent = parent.parent; Object.Destroy(parent.gameObject); GameObject go = new GameObject(); go.AddComponent <BoxCollider>(); go.transform.position = lowerPart.transform.position; upperPart.AddComponent <CapsuleCollider>().radius = 1; upperPart.AddComponent <Rigidbody>().AddForce(new Vector3(0, 0, -2 * game.speed.value), ForceMode.Impulse); Object.Destroy(go, 0.5f); Object.Destroy(upperPart, 2f); game.speed.value = 0; } else { Debug.Log("deleting obstacle because the player was there first"); entities[0].playerCollision.other.DestroyGameObject(); } foreach (var entity in entities) { entity.Destroy(); } }
// Start is called before the first frame update void Start() { toast = GameObject.FindGameObjectWithTag("Toast").GetComponent <Toast>(); foreach (float val in enemy_weights) { total += val; } remainingEnemies = 0; spawnPoint = transform.Find("SpawnPoint"); foreach (Collider2D col in Physics2D.OverlapCircleAll(VUtils.Vec3ToVec2(transform.position), 10)) { AIBoids ai = col.gameObject.GetComponent <AIBoids>(); if (ai) { remainingEnemies++; } } }
void EncompassPlayers() { float player_dispersion = PlayerManager.GetDispersion(); Collider2D col = Physics2D.OverlapPoint(VUtils.Vec3ToVec2(transform.position), LayerMask.GetMask("CameraInfo")); float min_z = MaxZoom; float max_z = MinZoom; if (col) { ForcedZoomComponent f = col.gameObject.GetComponent <ForcedZoomComponent>(); min_z = f.ZoomMin; max_z = f.ZoomMax; } player_dispersion = Mathf.Clamp(player_dispersion, MinPlayerDispersion, MaxPlayerDispersion); player_dispersion -= MinPlayerDispersion; player_dispersion /= MaxPlayerDispersion - MinPlayerDispersion; float zoom = min_z + player_dispersion * (max_z - min_z); Camera.main.orthographicSize = Mathf.Lerp(Camera.main.orthographicSize, zoom, TimeManager.deltaTime); }
public static GameObject GetClosestPlayer(Vector3 pos) { Vector2 pos2 = VUtils.Vec3ToVec2(pos); GameObject closest_player = null; float closest = Mathf.Infinity; if (Players.Count < 1) { return(null); } foreach (GameObject p in Players.Values) { if (Vector2.Distance(pos2, VUtils.Vec3ToVec2(p.transform.position)) < closest) { closest_player = p; closest = Vector2.Distance(pos2, VUtils.Vec3ToVec2(p.transform.position)); } } return(closest_player); }
public void DrawMap() { Color c = Color.blue; foreach (KeyValuePair <Vector2, NavNode> entry in NodeDict) { for (int i = 0; i < 8; ++i) { if (GetDir(entry.Value, i) != p_null) { Debug.DrawLine( VUtils.Vec2ToVec3(entry.Key), VUtils.Vec2ToVec3(GetDir(entry.Value, i)), c, 0, false ); } } } }
private void Update() { counter += TimeManager.deltaTime; if (counter >= Lifetime) { Explode(); } if (!target) { Vector3 closest_player = Vector3.up * 9999; foreach (GameObject player in PlayerManager.GetAllPlayers()) { if (Vector3.Distance(player.transform.position, transform.position) < Vector3.Distance(closest_player, transform.position)) { closest_player = player.transform.position; target = player.transform; } } } Vector3 targeting = (target.position - transform.position).normalized; rb.velocity = (rb.velocity + VUtils.Vec3ToVec2(targeting * 0.1f * SeekingStrength)).normalized * rb.velocity.magnitude; }
void Steering() { target = null; float min_dist = 9999; bool got_player = false; foreach (Collider2D col in Physics2D.OverlapCircleAll(VUtils.Vec3ToVec2(transform.position), PerceptionRadius)) { if (col.gameObject.CompareTag("Player")) { float dist = Vector3.Distance(transform.position, col.transform.position); if (dist < min_dist) { got_player = true; min_dist = dist; target = col.transform; } } if (!got_player && col.gameObject.CompareTag("Chester")) { target = col.transform; } } }
public static List <Vector3> NavBetween(Vector3 start_pos, Vector3 end_pos, int search_depth) { var path = new List <Vector3>(); Vector2 start = main.NavMap.GetNearestNode(VUtils.Vec3ToVec2(start_pos)); Vector2 end = main.NavMap.GetNearestNode(VUtils.Vec3ToVec2(end_pos)); if (start == NodeMap.p_null || end == NodeMap.p_null) { Debug.Log("Out of Boundaries"); return(path); } if (start.Equals(end)) { path.Add(VUtils.Vec2ToVec3(end)); return(path); } var open = new PriorityQueue <AStarNode>(AStarNodeComparator); // This hash function is arbitrary. However it must always return nonnegative values. var closed = new Dictionary <Vector2, AStarNode>(); Vector2[] successors; open.Add(new AStarNode { coords = start, f = 0F, g = 0F }); AStarNode finalNode = null; int searched_nodes = 0; while (open.Count > 0 && finalNode == null) { searched_nodes++; AStarNode cur = open.Pop(); Vector2 curCoords = cur.coords; // Generate successors and set parents to cur successors = main.NavMap.GetNeighbors(curCoords); // For each successor: foreach (Vector2 s in successors) { // If goal, stop // Debug.DrawLine( // VUtils.Vec2ToVec3(s), // VUtils.Vec2ToVec3(curCoords), // Color.magenta, // 0, // false // ); AStarNode next = new AStarNode { coords = s, parent = cur, g = cur.g + Vector2.Distance(s, curCoords) }; if (next.coords.Equals(end)) { finalNode = next; break; } if (Vector2.Distance(next.coords, end) < 0.3f) { Debug.Log(next.coords); } next.h = Vector2.Distance(next.coords, end); next.f = next.g + next.h; // If the tile is already in open, only keep the lower f Profiler.BeginSample("open find"); (int existingIndex, AStarNode existingOpen) = open.FindIndex(next); Profiler.EndSample(); if (existingIndex >= 0) { if (next.f < existingOpen.f) { open.ChangeKey(existingIndex, next); } continue; } // If noxel is already in closed with a lower f, skip if (closed.ContainsKey(next.coords)) { AStarNode c = closed[next.coords]; if (next.f < c.f) { closed.Remove(next.coords); } else { continue; } } // Add node to the open list open.Add(next); } closed.Add(cur.coords, cur); if (search_depth > 0 && searched_nodes >= search_depth) { break; } } if (finalNode == null) { // Path not found Debug.Log("No path found"); // Debug.Log("Nodes searched: " + searched_nodes.ToString()); return(path); } // Debug.Log("PATH FOUND!"); // Walk back along the path starting from final and store it in the return list AStarNode node = finalNode; while (!node.coords.Equals(start)) { path.Add(VUtils.Vec2ToVec3(node.coords)); node = node.parent; } path.Reverse(); // Debug.Log("Nodes searched: " + searched_nodes.ToString()); return(path); }
public void TearDown() { VUtils.getInstance().save(game.experience.level, game.experience.xp, game.score.highscore); }