Created
April 7, 2017 16:54
-
-
Save SampsonCrowley/b50b60615c62c93e9e377ccc23b49fd3 to your computer and use it in GitHub Desktop.
Asteroids Bullet Model
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Below is a section of code for creating and moving bullets in a canvas rendered asteroids game. | |
* | |
* Since asteroid ships can be facing a different direction than their movement direction, I needed | |
* to implement this model in a way that guaranteed bullets always fire in the direction the ship is facing. | |
* | |
* Multiple objects in the game are moveable, so code is simplified through Constructor inheritance. | |
* | |
* All functions are named for easier debugging | |
*/ | |
/* | |
* The ship function that creates bullets: | |
* | |
* this.fire = function fire(){ | |
* return new ASTEROIDS.Model.Bullet({ | |
* x: this.x, | |
* y: this.y, | |
* vx: this.dx(this.direction, 5), | |
* vy: this.dy(this.direction, 5), | |
* direction: this.direction, | |
* }) | |
* } | |
* | |
*/ | |
ASTEROIDS.Model.Moveable = function Moveable(coords) { | |
coords = coords || {}; | |
this.x = coords.x || ASTEROIDS.Model.height/2; | |
this.y = coords.y || ASTEROIDS.Model.width/2; | |
this.vx = coords.vx || 0; | |
this.vy = coords.vy || 0; | |
} | |
ASTEROIDS.Model.Moveable.prototype.tic = function(){ | |
this.x += this.vx; | |
this.y += this.vy; | |
return this.x + ", " + this.y; | |
} | |
ASTEROIDS.Model.Moveable.prototype.dx = function(theta, radius){ | |
return (radius || this.radius) * Math.cos(theta) | |
} | |
ASTEROIDS.Model.Moveable.prototype.dy = function(theta, radius){ | |
return (radius || this.radius) * Math.sin(theta) | |
} | |
ASTEROIDS.Model.moveBullets = function moveBullets(){ | |
for(var i = 0; i < this.bullets.length; i++){ | |
this.bullets[i].setVertices(); | |
this.bullets[i].tic() | |
if(this.screenWrap(this.bullets[i])){ | |
this.bullets.splice(i, 1) | |
} | |
} | |
} | |
ASTEROIDS.Model.Bullet = function Bullet(coords){ | |
this.direction = coords.direction; | |
this.radius = 5; | |
ASTEROIDS.Model.Moveable.call(this, coords); | |
this.setVertices = function() { | |
this.vertices = [ | |
[this.x + this.dx(this.direction), this.y + this.dy(this.direction)], | |
[this.x + this.dx(this.direction + Math.PI), this.y + this.dy(this.direction + Math.PI)], | |
] | |
} | |
} | |
ASTEROIDS.Model.Bullet.prototype = Object.create(ASTEROIDS.Model.Moveable.prototype); | |
ASTEROIDS.Model.Bullet.prototype.constructor = ASTEROIDS.Model.Bullet; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment