We are ready to start making some games with canvas
help, so in this first exercise we will a Car Race using some basic animations we learned today.
Remember you have the Learning Units to check any concept you might need. We are working with 2D
context, so you should think the canvas is a cartesian plane, where you can move elements changing their position in any of the axis
.
- Fork this repo
- Clone this repo into your
~/code/labs
- The images are also included in the repository
The first thing we need is to create our board. The left side of the image is already on the HTML file, but when we click on the StartGame button, we need to create the canvas and display our road.
The intrisic dimensions of the <canvas>
should be 1000x1600
You should add your drawing instructions inside the main.js
function draw() {}
.
Once we have our road, we need the player´s car. On the images
folder, you will find a .png
file you should use for the player.
You should use the Car
class:
- in the constructor, once image is loaded, assign
this.w
,this.h
,this.x
andthis.h
:this.x
should be 100 units as widththis.h
should be computed thanks toimgRatio
andthis.x
- Then implement the
draw()
method
Once our Car
class is ready, in main.js
don't forget to create a new car 🚗 when startGame()
! Don't also forget to draw it !
In our game, the player will only be able to move the car to the right and left. Using left
and right
arrows, the player should be able to move the car.
For that you should implement the 2 methods moveLeft()
and moveRight
of the Car
class.
💡 Remember the boundaries!
Now let´s make this interesting. We should create obstacles that shows up every certain amount of times. (Remember how we did them on the Learning Unit). In this iteration, just limit to create them 😉
They will always start in the position 0 of the y
axis, but you should make them appear in a random place of the x
axis.
You should use the Obstacle
class:
- in the
constructor()
, assignthis.w
,this.h
,this.x
andthis.h
- then implement the
draw()
method
NB: Implement a utility random(from, to)
function, to help you get random numbers for your obstacles.
Implement the hits()
method into Obstacle
class:
- it takes the car as parameter
- it should return a boolean wether the obstacle hits the car (or not).
NB: car hits an obstacle when car is in-between obstacle horizontally and vertically :)
Once hits()
implemented, test it against each obstacle in main.js
.
If one hits the car, pass gameover
to true
so it won't call requestAnimationFrame
next frame, ie: stop the gameloop.
Oh! If we want to challenge somebody, we need to quantify who is making it better. So we need to add a score. Go ahead and add a method to count points while you keep the car avoiding obstacles.