66 lines
2.8 KiB
JavaScript
66 lines
2.8 KiB
JavaScript
class bullet {
|
|
constructor(targetx, targety, radius, speed, shotPosX, shotPosY, hasMoved, angle) { // Add hasMoved parameter
|
|
// add all incoming variables to the class
|
|
this.angle = radians(angle);
|
|
this.targetx = targetx;
|
|
this.targety = targety;
|
|
this.x = shotPosX;
|
|
this.y = shotPosY;
|
|
this.radius = radius;
|
|
this.speed = speed;
|
|
this.bulletHit = false;
|
|
this.directionX = null;
|
|
this.directionY = null;
|
|
// Set a variable that cant be changed
|
|
if ((this.directionX === null) || (this.directionY === null)) {
|
|
this.directionX = this.targetx;
|
|
this.directionY = this.targety;
|
|
}
|
|
// create a vector for the projectile and the direction
|
|
this.projectile = createVector(this.x, this.y);
|
|
this.direction = createVector(this.targetx - this.projectile.x, this.targety - this.projectile.y);
|
|
this.direction.normalize();
|
|
// rotate the direction towards the player
|
|
this.direction.rotate(this.angle);
|
|
}
|
|
|
|
draw() {
|
|
//draw the bullet
|
|
push();
|
|
fill(0, 255, 0);
|
|
circle(this.projectile.x, this.projectile.y, this.radius);
|
|
pop();
|
|
}
|
|
|
|
update(targetx, targety, hasMoved, radius) {
|
|
// keeps the projetile updated so hit collision can be checked
|
|
this.targetx = targetx;
|
|
this.targety = targety;
|
|
// update the projectile
|
|
this.projectile.add(p5.Vector.mult(this.direction, this.speed));
|
|
|
|
let hit = false;
|
|
let shot = true;
|
|
let travelled = false;
|
|
// check if the projectile has hit the player
|
|
if (dist(this.projectile.x, this.projectile.y, this.targetx, this.targety) <= this.radius + radius) {
|
|
hit = true;
|
|
shot = false;
|
|
// if the projectile has hit the player and the player has lives left, remove a life
|
|
if (hasMoved && lives != 0 && this.bulletHit == false) {
|
|
this.bulletHit = true;
|
|
lives -= 1;
|
|
}
|
|
//if the bullet hits one of the wall reset the shot variable so a new wave of bullets can be fired
|
|
} else if (this.projectile.x < 0 - 10 || this.projectile.x > width + 10 || this.projectile.y < 0 - 10 || this.projectile.y > height + 10) {
|
|
shot = false;
|
|
}
|
|
// check if the projectile is off screen so it can be removed
|
|
let isOffScreen = this.projectile.x < 0 || this.projectile.x > width || this.projectile.y < 0 || this.projectile.y > height;
|
|
//unused variable to check if the projetile passsed the original player position when it was fired
|
|
let originalPos = this.projectile.x == this.targetx || this.projectile.y == this.targety;
|
|
|
|
// return all the variables
|
|
return { hit, shot, isOffScreen, originalPos };
|
|
}
|
|
} |