- Home /
2D platformer game enemy AI (simple patrol) problem. How to solve it (C#) ?
I wanted to make enemies whom can patrol with a given distance.
Everything is good until it reaches distance<=0
. I don't know what is wrong with it.
This is my code:
public class EnemyController : MonoBehaviour {
public float speed = 3f;
private float startingPositionX;
public float endingPositionX = 5f;
private float distance;
private float originalDistance;
private float originalPositionX;
void Start(){
startingPositionX = transform.position.x;
distance = endingPositionX - startingPositionX;
originalDistance = endingPositionX - startingPositionX;
originalPositionX = transform.position.x;
}
void FixedUpdate(){
if (distance >= 0) {
rigidbody2D.velocity = new Vector2 (speed, rigidbody2D.velocity.y);
distance = endingPositionX - transform.position.x;
print (distance);
}
else if (distance <= 0) {
startingPositionX = originalPositionX + endingPositionX;
endingPositionX =originalPositionX;
Flip ();
print ("elerte");
rigidbody2D.velocity = new Vector2 (-speed, rigidbody2D.velocity.y);
distance = Mathf.Abs(endingPositionX - transform.position.x);
}
}
void Flip(){
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
}
Answer by Inok · Jan 22, 2015 at 12:21 PM
Add Debug.Log to variables for find what cause problem. I think that problem or with distance calculation, so add Debug.Log(distance); or delete "=" from "else if".
I already did this but I used print("Elerte"). But I couldn't fix the problem
Answer by screenname_taken · Jan 22, 2015 at 12:24 PM
Weird, my answer is gone after it was converted from a comment. Anyway... your issue is in the if statements. You have both of them to check for being equal to 0 as well as being less or more. So there is a moment that both checks are true, when your distance goes to 0. Remove the "=" from one of the two. Probably on the first if.
Yes, I fixed it but not with this code. I made a whole new one. And I did a little AI: https://www.assetstore.unity3d.com/en/#!/content/28819
(I think this can help a lot :) )
Answer by GabeGabe · Aug 05, 2015 at 12:30 PM
SOLVED with this asset from the assetstore: https://www.assetstore.unity3d.com/en/#!/content/28819