- Home /
Top-Down Enemy Ai Animation
Hello, making a top-down 2D game, for my enemy ai animation, change the sprite without rotation, the code works fine, however does not identify all the "if" inside the "if (playerDistance <7f && playerDistance> 1.5f) "If I change the position of" if (currentPosition.lastPosition) "the ones that did not work start working and the previous ones do not work, usually the last 2 work. Should I enter some magnitude of the vectors? How to do this? Grateful.
public class Ai : MonoBehaviour {
public Transform player;
public float playerDistance;
public float moveSpeed;
public Transform target;
private Rigidbody2D myRigidbody;
private bool moving;
public float timeBetweenMove;
private float timeBetweenMoveCounter;
private float timeToMoveCounter;
public float timeToMove;
private Vector3 moveDirection;
public float waitToReload;
private bool reloading;
private GameObject thePlayer;
private Animator anim;
private Vector2 lastMove;
private Vector2 currentPosition;
private Vector2 lastPosition;
void Start () {
timeBetweenMoveCounter = Random.Range(timeBetweenMove * 1.25f, timeBetweenMove * 1.25f);
timeToMoveCounter = Random.Range(timeBetweenMove * 1.25f, timeBetweenMove * 1.25f);
myRigidbody = GetComponent<Rigidbody2D>();
reloading = false;
anim = GetComponent<Animator>();
currentPosition = transform.position;
lastPosition = currentPosition;
}
void Update () {
moving = false;
playerDistance = Vector2.Distance (player.position, transform.position);
if (playerDistance < 7f && playerDistance > 1.5f) {
moving = true;
transform.position = Vector3.MoveTowards (transform.position, player.position, Time.deltaTime * moveSpeed);
if (currentPosition.x > lastPosition.x) {
lastMove = new Vector2 (1f, 0f);
}
if (currentPosition.x < lastPosition.x) {
lastMove = new Vector2 (-1f, 0f);
}
if (currentPosition.y > lastPosition.y) {
lastMove = new Vector2 (0f, 1f);
}
if (currentPosition.y < lastPosition.y) {
lastMove = new Vector2 (0f, -1f);
}
} else if (playerDistance > 7f) {
//chase ();
}
lastPosition = currentPosition;
currentPosition = transform.position;
anim.SetFloat ("MoveX", lastMove.x);
anim.SetFloat ("MoveY", lastMove.y);
anim.SetBool ("moving", moving);
anim.SetFloat ("LastMoveX", lastMove.x);
anim.SetFloat ("LastMoveY", lastMove.y);
}
Comment
Your answer
Follow this Question
Related Questions
Hop from transform to transform in 2D game? 0 Answers
Getting the distance in a known direction 2 Answers
Making a character move automatically in one direction. 2 Answers
How to rotate object to cursor? 1 Answer
Move projectile in a specific direction 0 Answers