Move Game Objects
You already know variables and maths. Now use JavaScript to change where something is on the screen.
CSS 3.1 Gives Us a Movable Player
For JavaScript movement, the player needs position: absolute. Then left and top tell us where it is.
.game {
position: relative;
width: 600px;
height: 260px;
}
#player {
position: absolute;
left: 20px;
top: 90px;
}
1. A Function = Code You Can Run
A function gives a group of code a name. Later, a button can run it.
function sayHi() { }Give some code a name.sayHi()The brackets mean: run this function.onclick="sayHi()"Run it when the button is clicked.2. Find the Player
Before JavaScript can move an HTML element, it needs to find it. Give the element an id, then use getElementById.
document.getElementById("player") means: find the HTML element whose id="player".
3. Change left With JavaScript
If CSS can say left: 20px, JavaScript can change it to left: 100px.
player.style.left = "100px"; means: change the player's CSS left value to 100px.
"100px" to "200px", RUN, then click the button.4. Move Again and Again
A real movement button should move a little farther every time you click it. Store the position in a variable.
let x = 20;The player starts 20px from the left.x = x + 20;Add 20 every click.player.style.left = x + "px";Turn the number into a CSS value."px"?
JavaScript's x is a number such as 60. CSS needs a value such as 60px.
5. Right AND Left
Right adds to x. Left subtracts from x.
6. Add Up & Down
Horizontal movement uses left. Vertical movement uses top. So we need one more variable: y.
x → leftChange x to move left/right.y → topChange y to move up/down.number + "px"Both directions use the same idea.JS 2 Core Complete ✓
If you can make an object move with buttons, you have the main JS 2 skill.
functiononclickdocument.getElementById()element.style.leftelement.style.top- use
xandyvariables - add/subtract movement
- add
"px"to a number
Mini Challenge: Reach the Target
Make a player and a target. Use your four movement buttons to move the player toward the target.
<div class="game">
<img id="player" src="../rocket.png">
<div id="target">⭐</div>
</div>
<button onclick="moveUp()">UP</button>
<button onclick="moveLeft()">LEFT</button>
<button onclick="moveRight()">RIGHT</button>
<button onclick="moveDown()">DOWN</button>
JS 2 Memory Map
function move() { }Create code you can run.onclick="move()"Run a function on click.getElementById("player")Find an HTML element.let x = 20;Remember horizontal position.x = x + 20;Move right.x = x - 20;Move left.style.leftChange horizontal CSS position.style.topChange vertical CSS position.x + "px"Turn a number into a CSS size.