I did exactly as you said and tried tweaking it a few times. I couldn’t get it to work. Undoubtedly an error on my part, but looking at your code, it seems that, should the mouse move towards the character, the walking animation will trigger. I only want the animation to play when the character moves, not when the change in distance is caused by the mouse being moved toward the character. Jacob’s solution is
good; it helps me a lot. Of course, it still leaves the problem of determining when the character moves. This is what I have tried to do:
public class Player extends Entity{
public var sprPlyr:Spritemap = new Spritemap(Assets.Plyr, 128, 128);
private var lastDistance:Number = 0
private var moveDir:Number = 0
private var moveKeyPressed:Boolean = false
public function Player()
{
sprPlyr.add("walk", [0, 1, 2, 3, 4, 5, 6, 7], 20, true);
graphic = sprPlyr;
}
override public function update(): void
{
if (Input.check(Key.A)) { x -= 2 };
if (Input.check(Key.D)) { x += 2 };
if (Input.check(Key.W)) { y -= 2 };
if (Input.check(Key.S)) { y += 2 };
if (Input.pressed(Key.A)) { moveKeyPressed = true }
else if (Input.pressed(Key.D)) { moveKeyPressed = true }
else if (Input.pressed(Key.W)) { moveKeyPressed = true }
else if (Input.pressed(Key.S)) { moveKeyPressed = true }
else (moveKeyPressed = false)
sprPlyr.originX = sprPlyr.width / 2;
sprPlyr.originY = sprPlyr.height / 2;
sprPlyr.angle = FP.angle(Input.mouseX, Input.mouseY, x, y) + 90;
var distance:Number = FP.distance(x, y, Input.mouseX, Input.mouseY);
if (distance > lastDistance) {moveDir = -1};
if (distance < lastDistance) {moveDir = 1};
if (moveKeyPressed == true && moveDir == 1) {sprPlyr.play("walk", false, 0)}
else { sprPlyr.play("stand", false, 0) }
lastDistance = distance
}
}
I tried using a variable to
determine if one of my movement keys (WASD) was pressed and another
variable to determine if the character was moving toward or away from
the mouse. I then used conditionals to determine whether to play the
forward walking animation. For some reason, that isn’t working.Just to be clear, I don’t have a backward walking animation yet, not that that’s important.