Hey guys,
I've just recently purchased the 2D Toolkit, and am pretty impressed so far! However, I'm a bit stuck with something.
My issue is that I have a sprite that I can move around with WASD. When not moving, there is an idle animation. The sprite can move in 8 directions, however there are only animations for the up,down,left,and right. My goal is to have the player face up if W+D or W+A is pressed, and down if S+A or S+D is pressed. However, I'm not quite sure how to do this. In addition, when the player lets go of say the up key and starts walking right or left, I'd like the frame to change to be right or left.
Right now I do my movement in a method called move() which is called by the player's Update() method.
Here is the code, which clearly doesn't work as intended, nor does it even attempt to currently make the player face up/down when moving diagonally.
// Player Movement
void move() {
// UP
if (Input.GetKey(KeyCode.W))
{
direction = 0;
this.transform.position = new Vector3(this.transform.position.x, this.transform.position.y + 1, 0);
}
// LEFT
if (Input.GetKey(KeyCode.A))
{
direction = 1;
this.transform.position = new Vector3(this.transform.position.x - 1, this.transform.position.y, 0);
}
// DOWN
if (Input.GetKey(KeyCode.S))
{
direction = 2;
this.transform.position = new Vector3(this.transform.position.x, this.transform.position.y - 1, 0);
}
// RIGHT
if (Input.GetKey(KeyCode.D))
{
direction = 3;
this.transform.position = new Vector3(this.transform.position.x + 1, this.transform.position.y, 0);
}
// IDLE
if (Input.GetKeyUp(KeyCode.W) || Input.GetKeyUp(KeyCode.A) ||
Input.GetKeyUp(KeyCode.S) || Input.GetKeyUp(KeyCode.D))
{
pSprite.Play("idle");
pSprite.animationCompleteDelegate = null;
walk = false;
}
// WALKING ANIMATIONS
if (Input.GetKeyDown(KeyCode.W))
{
pSprite.Play("walk_up");
pSprite.animationCompleteDelegate = null;
walk = true;
}
if (Input.GetKeyDown(KeyCode.A))
{
pSprite.Play("walk_left");
pSprite.animationCompleteDelegate = null;
walk = true;
}
if (Input.GetKeyDown(KeyCode.S))
{
pSprite.Play("walk_down");
pSprite.animationCompleteDelegate = null;
walk = true;
}
if (Input.GetKeyDown(KeyCode.D))
{
pSprite.Play("walk_right");
pSprite.animationCompleteDelegate = null;
walk = true;
}
}
I also have an attack animation which plays, which is why the direction variable is primarily used (so the delegate knows which direction to resume going to while attacking when moving).
Right now when you press S+D and then release one of the keys to move either down or right, the idle animation plays while moving.
Any help would be appreciated. If anything is unclear, let me know!