Skip to content

Instantly share code, notes, and snippets.

@nickgs
Created May 21, 2020 01:32
Show Gist options
  • Save nickgs/9ebe7a0e9331d49f1194be191f0c2464 to your computer and use it in GitHub Desktop.
Save nickgs/9ebe7a0e9331d49f1194be191f0c2464 to your computer and use it in GitHub Desktop.
ShipShooter.js Spring 2020
let ship;
let enemies = [];
function setup() {
createCanvas(windowWidth, windowHeight);
background("black");
ship = new Ship(windowWidth / 2, windowHeight / 2);
}
function draw() {
background('black');
if(frameCount % 100 == 0) {
enemies.push(new Enemy(random(windowWidth), -10));
}
for(let i = 0; i < enemies.length; i++) {
enemies[i].update();
enemies[i].draw();
}
ship.update();
ship.draw();
if(keyIsDown(32)) {
ship.fire();
}
}
class Ship {
constructor(x, y) {
this.x = x;
this.y = y;
this.bullets = [];
}
draw() {
fill("white");
triangle(this.x, this.y, this.x - 10, this.y + 30, this.x + 10, this.y + 30);
for(let i = 0; i < this.bullets.length; i++) {
this.bullets[i].draw();
this.bullets[i].update();
}
}
update() {
//if(keyIsPressed === true) {
console.log(keyCode);
// this code will execute when a key is held down.
if(keyIsDown(LEFT_ARROW)) {
// if the user hits the left arrow, this block of code will execute.
this.x -= 3;
}
if(keyIsDown(RIGHT_ARROW)) {
// if the user hits the left arrow, this block of code will execute.
this.x += 3;
}
if(keyIsDown(UP_ARROW)){
// if the user hits the left arrow, this block of code will execute.
this.y -= 3;
}
if(keyIsDown(DOWN_ARROW)) {
// if the user hits the left arrow, this block of code will execute.
this.y += 3;
}
//}
}
fire() {
this.bullets.push(new Bullet(this.x, this.y));
}
}
class Bullet {
constructor(x, y) {
this.x = x;
this.y = y;
}
update() {
this.y-=5;
}
draw() {
console.log("DRAWING");
stroke("red");
line(this.x, this.y, this.x, this.y - 10);
}
}
// Lets describe an enemy
class Enemy {
constructor(x, y) {
this.x = x;
this.y = y;
}
update() {
this.y = this.y + 1; // this.y++
}
draw() {
fill("blue");
rect(this.x, this.y, 20, 20);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment