- Home /
Enemy Movement Help
I am working on a topdown 2D game and was testing it when I saw that the enemies that spawned went to where the player was placed before it started moving. My code for the enemy movement is using UnityEngine; using System.Collections; public class EnemyMotion : MonoBehaviour { public float speed; public Transform player; void FixedUpdate() { float z = Mathf.Atan2 ((player.transform.position.y - transform.position.y), (player.transform.position.x - transform.position.x)) * Mathf.Rad2Deg - 90; transform.eulerAngles = new Vector3 (0, 0, z); rigidbody2D.AddForce (gameObject.transform.up * speed); } }
Please Help
Is player assigned correctly in the inspector?
If it is I would try add Debug.Log(z) at about line 9 and make sure that z is updating correctly as the player moves around.
Answer by Pyrian · May 28, 2014 at 09:27 PM
Change "public Transform player" to "public GameObject player". You want the enemies to follow the player's current position, not where he was before the game even starts.
This didn't change anything. The enemy's that start on the screen work just as they are meant to but the ones from the spawner go to where the player was placed before the game started regardless of where the player is.
Transform is also updated each frame and is the correct place to reference for getting position.
Try making sure it's set correctly when the new wave spawns. Since player is public, you should be able to set it by the spawner. Alternatively, you could do a tag search in the Start of the enemy, but that would be less efficient.
Answer by jcoder · May 28, 2014 at 03:29 AM
I don't really see why it's a problem if the enemies follow the player when the player isn't moving. Maybe you meant the player wasn't active?
public GameObject player;
void FixedUpdate()
{
if(player.activeInHierarchy)
{
//follow player
}
}
They go to where the was placed before he started moving and only the first wave follows him.
Format code jcoder!
Highlight and click 1010101
Ill do this one for you
Answer by meat5000 · May 29, 2014 at 02:07 AM
public Transform player;
alone is not enough to retrieve updated information.
Your enemy will, in Start(), require to 'Find' the player Object and you will need to GetComponent(Transform) the result.
Any subsequent call to the players information will herald updated information.
Your answer
Follow this Question
Related Questions
Making a bubble level (not a game but work tool) 1 Answer
How can I make 2D movement less jerky on a controller, with velocity and such? 0 Answers
2D camera zoom smoothing and limitations? 1 Answer
Enemy Knockback when hit player 2D Topdown 1 Answer
How to make sprites in SideScroller move in smooth curves 0 Answers