Code:
using UnityEngine;
using System.Collections;
public class enemyAI : MonoBehaviour
{
private Rigidbody2D myRigidbody;
private bool moveRight;
private Vector2 moveLocation;
[SerializeField]
private float speed;
[SerializeField]
private Vector2 tra1;
[SerializeField]
private Vector2 tra2;
// Use this for initialization
void Start()
{
myRigidbody = GetComponent();
moveRight = true;
}
// Update is called once per frame
void FixedUpdate () {
Debug.Log(moveRight);
tra1 = transform.position;
EmemyMovement();
tra2 = transform.position;
if (tra1.x == tra2.x)
{
moveRight = !moveRight;
}
}
private void EmemyMovement()
{
if (moveRight == true)
{
moveLocation = new Vector2(transform.position.x + speed, transform.position.y);
myRigidbody.MovePosition(moveLocation);
}
else
{
moveLocation = new Vector2(transform.position.x + -speed, transform.position.y);
myRigidbody.MovePosition(moveLocation);
}
}
}
It should be that it moves right until it stops then it moves left but when I run it the variable moveRight changes between true and false every frame and bounces forwards and backwards. Any help?
↧