Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var canvas = document.getElementById('canvas');
- var ctx = canvas.getContext('2d');
- var ship = new Ship();
- var bullets = [];
- function allUpdate(){
- drawBackground();
- ship.update();
- //for loop to draw all bullets
- for(var i =0;i < bullets.length;i++){
- var bullet = bullets[i];
- bullet.update();
- }
- window.requestAnimationFrame(allUpdate);
- }
- window.requestAnimationFrame(allUpdate);
- window.onkeydown = function(event){
- var left = 37;
- var up = 38;
- var right = 39;
- var down = 40;
- if(event.keyCode == up)
- ship.dY = -1;
- if(event.keyCode == down)
- ship.dY = 1;
- if(event.keyCode == left){
- ship.isRotating = true;
- ship.theta = -5;
- }
- if(event.keyCode == right){
- ship.isRotating = true;
- ship.theta = 5;
- }
- if(event.key == " "){
- var x = ship.x + ship.width;
- var y = ship.y + ship.height/2;
- var bullet = new Bullet(x,y);
- bullets.push(bullet);
- }
- }
- window.onkeyup = function(event){
- var left = 37;
- var up = 38;
- var right = 39;
- var down = 40;
- if(event.keyCode == left || event.keyCode == right){
- ship.isRotating = false;
- ship.theta = 0;
- }
- }
- var Bullet = function(x,y){
- this.x = x;
- this.y = y;
- this.r = 5;
- this.dX = 2;
- this.dY = 2;
- this.update = function(){
- ctx.fillStyle = "blue";
- ctx.beginPath();
- ctx.arc(this.x+=this.dX,this.y,this.r,0,Math.PI *2,false);
- ctx.closePath();
- ctx.fill();
- }
- }
- function Ship(){
- this.isRotating = false;
- this.theta = 0; //in degrees
- this.width = 30;
- this.height = 10;
- this.x = 0;
- this.y = canvas.height/2;
- this.dX = 1;
- this.dY = 0;
- this.fillStyle = "white";
- this.update = function() {
- ctx.fillStyle = "white";
- ctx.fillRect(this.x+=this.dX,this.y+=this.dY,this.width,this.height);
- ctx.translate(this.x,this.y+(this.height/2));
- ctx.rotate((this.theta) * Math.PI/180);
- ctx.translate(-this.x,-(this.y +this.height/2));
- }
- }
- function drawBackground(){
- ctx.fillStyle = "black";
- ctx.fillRect(0,0,canvas.width,canvas.height);
- }
Add Comment
Please, Sign In to add comment