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?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | 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); } } |