This course will become read-only in the near future. Tell us at community.p2pu.org if that is a problem.

Exercises for Week 1 - Player Input


Task 2 part 1 (Easy) - Make a character move around the page in response to the arrow keys.

Modify the code you wrote in the signup task.  Add an <img> of a player character avatar to the page. (Your choice - either draw something - stick figures are fine if you're not an artist! - or use a creative-commons-licensed image file from the web).  Make it so that when a user hits an arrow key, instead of adding text to the screen, the image moves in the appropriate direction.

Hint - you'll probably want to use variables for the x and y coordinates of the image, and change the CSS properties of the image node to set its position.

 

Task 2 part 2 (A little harder) - Make the character follow the mouse around the page.

Copy the code from assignment 1 and modify it so that the avatar is controlled by the mouse instead of the keyboard.  You'll need to respond to "mousemove" events.  When the mouse position is outside of the avatar image, your code will need to figure out which direction the image needs to move in to get closer to the mouse position.  The image should then move smoothly in that direction until it reaches the mouse position, then stop.

Hint - you'll need to store the mouse x and y coordinates in response to mousemove events, but you'll find that if you try to move the avatar image in your mousemove event handler, then it will stop moving as soon as the player stops moving the mouse.  That's not what you want, so you'll have to have another function that moves the avatar, and make sure this function gets called repeatedly whether the mouse is moving or not.

Task Discussion