Now to add some proper interaction to your game.
-
Inspect the code [0 marks]
-
Create variables for interaction [1 marks]
- Declare four variables:
isLeft
,isRight
,isFalling
andisPlummeting
- Initialise each of them to
false
. These variables will be used to animate your game character.
- Declare four variables:
-
Implement left and right for keyPressed [1 marks]
- Inside the function
keyPressed
write twoif
statements such that: when the left arrow key is pressed,isLeft = true
; when the right arrow key is pressed,isRight = true
. - Test your conditional statements using
console.log()
to see the values of isLeft and isRight - Hint: look up the difference between
keyCode
andkey
to help you decide which variable you need to use.
- Inside the function
-
Implement left and right for keyReleased [1 marks]
- Inside the function
keyReleased
write twoif
statements such that: - when the left arrow key is released,
isLeft = false
; - when the right arrow key is released,
isRight = false
. - Test your conditional statements using
console.log()
to see the values of isLeft and isRight
- Inside the function
-
Add game character [1 marks]
- Add your game character code from part 2 to this sketch.
- You need to place each block of character code within the appropriate
if
statement so that when the character is animated the correct image will be drawn.
-
Make the game character move left and right [2 marks]
- In the
draw
function add twoif
statements such that: - when
isLeft
istrue
the character moves to the left; - when
isRight
istrue
the character moves to the right. - Test that your character moves left, right, and stops correctly when the arrow keys are pressed and released.
- HINT: you need to use the
isLeft
,isRight
, andgameChar_x
variables.
- In the
-
Make the game character jump [2 marks]
- Add another
if
statement withinkeyPressed
that checks when the the space-bar is pressed. - When the condition is met subtract 100 from
gameChar_y
so that the character jumps up in the air. - Now adjust your conditional statement so that your character can only jump when
it is touching the ground. HINT: use
gameChar_y
variable in your condition.
- Add another
-
Add gravity [2 marks]
- Add an
if
statement withindraw
to detect when the character is above ground level. HINT: usefloorPos_y
andgameChar_y
in your condition - When the condition is met increment
gameChar_y
so that the character falls towards the ground. Also setisFalling
totrue
so that the falling image of the character appears - Now add an
else
action to your conditional statement which setisFalling
tofalse
- Add an
-
Testing your interaction [0 marks]
- Make sure the correct character images appear when you move left, move right, jump left and jump right
- Make sure that game character falls immediately after you press the space bar and that you can't jump again until they have touched the ground