- Home /
Unity Enemy Range detection
I'm building a 2D game on Unity for my schoolproject and i'm currently working on enemies, who are suppose to within a certain range of the player, start following the player. Im using C#
I've just added the script so the enemy follows the players x position.
I was thinking that it should be something like this but other than that i have no idea...
if (transform.position.x = player.transform.position.x + 10)
{
if (transform.position.x > Player.transform.position.x)
{
Controller.Move(Vector3.left EnemySpeed Time.deltaTime);
}
else if (transform.position.x < Player.transform.position.x)
{
Controller.Move(Vector3.right EnemySpeed Time.deltaTime); }
}
Thanks for reading and i would appreciate any help you can give :)
Answer by jakovd · Mar 07, 2012 at 10:29 AM
First of all, if you are doing it with Unity - it's a 3D game :) You may look at the scene with a ortographic view, and program it so that you ignore one axis, but it will still be represented as a 3D.
I can suggest you a better solution for your idea. You can subtract enemy position form player position to get a vector of direction from enemy to player. Then just move an enemy in that direction (multiplied with speed and deltaTime.) Why are you using Controller on enemies? If you need just that primitive "go-straight-toward-player" behaviour you can just move them by adding that direction to their transform.position value. Or, use rigidbodies on them and add force in that same direction.