Finding out GameObject Move Direction

Hey guys, I’m trying to set up some animations that automatically play if my GameObject moves across a certain axis in a 2D RPG I’m working on.

For instance, if he moves up the +y axis then I know he’s moving up and can play his up walk up animation. if he’s moving -y then I know he’s moving down and can play his down walk animation and so on.

Does anyone have any ideas by chance about how to approach that? I’m using the 2D Toolkit plugin which has been wonderful so far, thanks!

2 Answers

2

Well, you’re already answering your own question here! You always have access to transform.position, and if you wanted an approximation of velocity, you could store the previous location, and compare that with the current location every frame, like so

var prevLoc : Vector3 = Vector3.zero;

function Update()
{
    var curVel : Vector3 = (transform.position - prevLoc) / Time.deltaTime;
    if(curVel.y > 0)
    {
        // it's moving up
    } else {
        // it's moving down
    }
    prevLoc = transform.position;
}

Haha! I didn't even see that! I was trying to separate it out to another script, but it's much easier to just have it all on the same script, thanks!

The division for Time.deltaTime is useless.

how would this work if vector3.0 = 0,0,0, then if u move up to a certain point then fall down, then ull still be above zero and moving up, right?

The simpler solution could be to “watch” the controls and start the animation accordingly to the controls used. If you move your character along the Y axis using the “Vertical” axis (W, S, up and down arrows) you can do something like this inside Update:

...
var controlY = Input.GetAxis("Vertical");
if (controlY > 0){
    animation.CrossFade("WalkUp");
}
if (controlY < 0){
    animation.CrossFade("WalkDown");
}
...

But if you really need to use the velocity, you must track it using Update:

var lastPos: Vector3;

function Start(){
    lastPos = transform.position;
}

function Update(){
    var velocity = transform.position - lastPos;
    lastPos = transform.position;
    if (velocity.y > 0.1){
        animation.CrossFade("WalkUp");
    }
    if (velocity.y < -0.1){
        animation.CrossFade("WalkDown");
    }
}

I actually have something going like this for my Controlled character, what I was need was something that worked for NPC's / Monsters. This one works perfect for Controlled characters though.