Asteroids Session 3 of 3
Part 4: Firepower 60 Minutes
We’ve now created a fun game of dodgeball! We’re sitting ducks without some way to fight back.
To fire a bullet, we'll create a new circle at the location of our spaceship and send it flying. We'll attach this code to the "space" event.
function fire() {
let x = spaceship.x
let y = spaceship.y
let bullet = circle(x, y, 5)
bullet.speed = 5
bullet.direction = spaceship.angle
}
on('space', fire)
And remove anything the bullet comes in contact with. We can achieve this by again listening for the "collision" event, this time on the bullet.
function fire() {
let x = spaceship.x
let y = spaceship.y
let bullet = circle(x, y, 5)
bullet.speed = 5
bullet.direction = spaceship.angle
bullet.on('collision', hit)
}
on('space', fire)
function hit(target) {
target.remove()
this.remove()
}
For collision events, the event handler is passed a parameter
containing the object we collided with. We can call the
remove()
method on this object to get rid of it.
We also want to get rid of the bullet itself. Here we'll use the
infamous JavaScript keyword this
. this
is one
of the most misunderstood concepts in JavaScript, as it can mean
different things at different times. In an event handler it refers to
the object that triggered the event, in this case the bullet.
Houston, we have another problem! Since the bullet starts at our ship’s position, we end up blowing ourselves up. We need to start the bullet at a distance from our ship. The question is, how do we determine that position?
Trigonometry
Early mathematicians recognized something else. As you move around a circle, the x and y coordinates follow a predictable wave-like pattern. These are referred to as sine and cosine.
Using this knowledge, we can work a little math-magic to determine where to place the bullet, given the angle of the spaceship and a safe distance.
function fire() {
let direction = ship.angle * Math.PI / 180
let distance = 5
let x = spaceship.x + Math.cos(direction) * distance
let y = spaceship.y + Math.sin(direction) * distance
let bullet = circle(x, y, 5)
bullet.speed = 5
bullet.direction = spaceship.angle
bullet.on('collision', hit)
}