xxxxxxxxxx
114
let bullets = [];
let fireTimerMS = 0;
const fireTimerMSMax = 100;
const bulletSpeed = 500;
let currTime = 0, prevTime = 0;
let prevMouseX = 0, prevMouseY = 0;
let player;
function setup() {
createCanvas(400, 400);
player = new Player(width/2, height/2);
}
function draw() {
background(50);
prevTime = currTime;
currTime = millis();
const delta = currTime - prevTime;
player.update(delta);
player.draw();
shoot(delta);
bullets = bullets.filter(bullet => {
const dead = bullet.update(delta);
bullet.draw(delta);
return !dead;
});
}
function shoot(delta) {
if(fireTimerMS > 0) {
fireTimerMS -= delta;
}
if(canFire()) {
fire();
}
}
function canFire() {
return mouseIsPressed && fireTimerMS <= 0;
}
function fire() {
const vel = player.vel.copy();
vel.setMag(bulletSpeed);
bullets.push(new Bullet(player.x, player.y, vel.x, vel.y));
fireTimerMS = fireTimerMSMax;
}
class Bullet {
constructor(x, y, vx, vy) {
this.x = x;
this.y = y;
this.vx = vx;
this.vy = vy;
}
update(delta) {
this.x += this.vx * (delta/1000);
this.y += this.vy * (delta/1000);
return this.x < 0 || this.x > width || this.y < 0 || this.y > height;
}
draw(delta) {
stroke(0, 255, 255);
strokeWeight(2);
line(this.x, this.y, this.x + (this.vx * delta/1000), this.y + (this.vy * delta/1000));
}
}
class Player {
constructor(x, y) {
this.x = x;
this.y = y;
this.vel = createVector(0, 0);
this.maxVel = 2;
this.maxForce = 1;
}
update(delta) {
const desired = createVector(mouseX - this.x, mouseY - this.y);
desired.setMag(this.maxVel);
const steering = desired.copy().sub(this.vel);
if(steering.mag() > this.maxForce) {
steering.setMag(this.maxForce);
}
this.vel = this.vel.add(steering);
this.x += this.vel.x;
this.y += this.vel.y;
}
draw() {
stroke(255);
circle(this.x, this.y, 10);
}
}