I want to play a sound when my player is walking, this is the code I have for the checkMovement method. How do I make it to where the walking sound plays when I press w or a or s or d and then stops when I release the keys?
private void checkMovement() {
// Gets the exact location.
double x = getExactX();
double y = getExactY();
// Stores the original location so that the player can stay in that location whenever they try to go through an object that they aren't supposed to.
double originalX = x;
double originalY = y;
GreenfootSound walking = new GreenfootSound("walking.mp3");
// Move up whenever the "w" key is pressed.
if (Greenfoot.isKeyDown("w")) {
y -= speed;
}
// Move down whenever the "s" key is pressed.
if (Greenfoot.isKeyDown("s")) {
y += speed;
}
// Move left whenever the "a" key is pressed, while also flipping the player to face the left.
if (Greenfoot.isKeyDown("a")) {
x -= speed;
if (facingRight) {
flipImage();
facingRight = false;
}
}
// Move right whenever the "d" key is pressed, while also flipping the player to face the right.
if (Greenfoot.isKeyDown("d")) {
x += speed;
if (!facingRight) {
flipImage();
facingRight = true;
}
}
// Temporarily move to the new location to test for collisions.
setLocation(x, y);
// Return to the original position if colliding with a Tree.
if (isTouching(Tree.class)) {
setLocation(originalX, originalY);
}
// Return to the original position if colliding with a Barrier.
if (isTouching(Barrier.class)) {
setLocation(originalX, originalY);
}
}
