Objects - Moving on Their Own Now that we have a player that we can move with the arrowkeys, we need a moving enemy to avoid. Moving targets add excitement and danger to a game. You can use any of the games that you made before, or start with a new one. For this example, I am going to use the Maze game that a student made. It is a simple maze that we want to add more action to. Right now, the prince has to make it through the maze to rescue the princess. We are going to add a moving dragon that he will have to avoid while going through the maze. First we add a button and call it Dragon (we will skin it with an image of a dragon later) Right not now, it will just be a black button (black square) Now to add the code for the dragon to move. We will add it on to the 'card script' but not inside the 'arrowKeys' handler. We don't want it to move only when we move. We want it to move on it's own. So we will create a handler - "moveDragon" of its own. The handler "moveDragon" will move the button "dragon" to the left everytime it receives the "moveDragon" message. Note that it is outside the arrowKey handler because we want the dragon to move on its own and not wait until someone presses an arrowKey. (Also notice that we have 2 intersects - one for when the prince runs into the maze walls and the other for when the prince reaches the 'Finish" line ) But we are not finished. The dragon will keep moving to the left, forever. We need to detect when it reaches the left side of the card and start it again on the right side of the card. Now the dragon will move, only once. We have to keep sending "moveDragon" messages to it to keep it moving. We can have the dragon send itself the "moveDragon" message. Change the code to say: We are not done yet. If you notice, there is no way to stop the dragon from moving. It keeps sending the message and never stops. So after the game is over, the dragon will still be moving. So we need to add "Start" and "Stop" buttons. We also need to create a global variable (called "playGame") that will tell the dragon when the game is over. Add 2 buttons with the following code: The Start button will send the message: "startGame" and the stop button will send "stopGame" Now back to the CARD SCRIPT to add the message handlers to the card script and create a global called "playGame" Add the global variable - playGame to the top of the CARD SCRIPT Add the new message handlers - "startGame", "stopGame" and change the "moveDragon" to check the variable "playGame" before sending another message to move again Finally, lets add code to check if the button "box" intersects with the button "Dragon" |
Game Programming >










