- Home /
Enemy Moves only to One Side
Hello Recently, I've went through the Space Shooter tutorial here on the web page. After finishing that, I wanted to add enemies, which will stafe left and right in order to be in front of the player. I've managed to make the script work on 50%. That is, the enemy moves towards the player only when he is to the left. Does anyone see, where the problem is? Thanks for reply.
public GameObject player;
public float speed;
public float forwardSpeed;
void FixedUpdate () {
if(player.transform.position.x > transform.position.x)
{
rigidbody.velocity = new Vector3(speed, 0f, forwardSpeed);
}
if (player.transform.position.x < transform.position.x)
{
rigidbody.velocity = new Vector3(-speed, 0f, forwardSpeed);
}
else
{
rigidbody.velocity = new Vector3(0f, 0f, forwardSpeed);
}
}
EDIT// I've concluded that the problem is the else line. If I remove that piece of code, the enemy strafes correctly against the player, but once he gets into the "sweet spot" he starts shaking left and right, as the script moves him out there and gets updated. Any help on that?
Answer by EHogger · Jan 02, 2014 at 01:34 AM
The second if
should be else if
.
At the moment, the else statement is only relating to the second if statement, so even if the first if assessment was true, the else is also getting applied.
Answer by Teplak · Jan 02, 2014 at 07:45 PM
I see, looks like I've taken some of my php habits with me, totally missed that one :D thank you.
Your answer
Follow this Question
Related Questions
Multiple enemy prefabs moving towards a single goal. Need help! 1 Answer
More efficient way to spawn enemies in my game...? 2 Answers
AI controller script, Enemy movement issues 0 Answers
Enemy move error 2 Answers
How to make RigidBody's movement using fixed movement/velocity and other forces all together? 3 Answers