2D enemy movement direction
I'm a rookie when it comes to coding and I'm making a simple top-down 2D game. I have an enemy which exists out of a sprite. I have 4 different sprites where the enemy faces different directions.
I'm using a pathfinding script (Poly|Nav in Asset Store) which moves the character to wherever I am clicking on my screen. This works fine, but I want the enemy sprite to change depending on which direction the enemy is facing. I have tried the following Javascript. The code does change the sprite but it never uses all of them. So the enemy might be facing to the right whilst going down, etc. Any ideas?
I did notice that for example when moving downwards + a bit to the left, it will try and face both down and left at the same time because both X and Y axis are changing. Is there a way to solve this? I thought maybe it's possible to calculate which number is more dominant and base it off that, just not sure how to do that and if that would work.
#pragma strict
var prevLoc : Vector3 = Vector3.zero;
public var NPCMoveUp : Sprite;
public var NPCMoveDown : Sprite;
public var NPCMoveLeft : Sprite;
public var NPCMoveRight : Sprite;
InvokeRepeating("NPCMoving", 0, 2);
function Update(){
var curVel : Vector3 = (transform.position - prevLoc) / Time.deltaTime;
if(curVel.y > 0){
GetComponent(SpriteRenderer).sprite = NPCMoveUp;
}
if(curVel.y < 0){
GetComponent(SpriteRenderer).sprite = NPCMoveDown;
}
if(curVel.x > 0){
GetComponent(SpriteRenderer).sprite = NPCMoveRight;
}
if(curVel.x < 0){
GetComponent(SpriteRenderer).sprite = NPCMoveLeft;
}
}
function NPCMoving(){
prevLoc = transform.position;
}
Maybe it's not possible the way I am trying it right now? I don't know how to solve this. Thanks for your time and help.
Your answer
Follow this Question
Related Questions
2D Top Down, Enemy facing player slow rotation issue. Vector gets messed up after collision. 3 Answers
Constraning an object's forces to only two directions in 2D (or infinite friction?) 0 Answers
Sprites moving (shaking) during animation while they should not 1 Answer
2D moving Script 1 Answer
Moving an object to a direction in degrees at a specific speed? 0 Answers