Quantcast
Channel: Questions in topic: "enemy"
Viewing all articles
Browse latest Browse all 1488

I need help with Enemy following my Player

$
0
0
Hello everyone, this is kind of a specific question, so will try to clarify as much as I can. I have a 2D top shooter game, where I instantiate Enemies from different points and they follow my Player until they touch him and kill him. I already have set colliders, spawning points and the wave spawner and the enemies do follow properly the Player, but only when they already start in the game itself. When I instantiate them they all start without the variable referenced that they have to specifically follow the player(its transform). So I made a prefab of the player and made them reference that. However now the enemies that I instantiate they go towards the original Transform point where my Player started and thats it, they never keep on looking for the new position the Player has, only the original position when game started. The script for the enemy and its movement is the following: public class Enemy : MonoBehaviour { public Transform player; public float moveSpeed = 4f; private Vector2 movement; private Rigidbody2D rbEnemy; // Start is called before the first frame update void Start() { rbEnemy = this.GetComponent(); } // Update is called once per frame private void Update() { Vector3 direction = player.position - transform.position; float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg - 90f; rbEnemy.rotation = angle; direction.Normalize(); movement = direction; } private void FixedUpdate() { moveCharacter(movement); } void moveCharacter(Vector2 direction) { rbEnemy.MovePosition((Vector2)transform.position + (direction * moveSpeed * Time.deltaTime)); } private void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.tag == "Player") { Destroy(GameObject.FindGameObjectWithTag("Player")); } } }

Viewing all articles
Browse latest Browse all 1488

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>