xxxxxxxxxx
65
// player position defined by px and py
let px = 200;
let py = 200;
// this shows where player is facing
let angle = 0;
// array to keep track of all the bullets
let bullets = [];
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
// this is the player. since it was just a circle with no movement, i didn't bother making a seperate object for it
push();
noStroke();
fill(51);
ellipse(px, py, 30);
pop();
// angle is calculated here. you don't need to worry about the function atan2. Values put there should be like: atan2(y position of desired bullet position - current y position, x position of desired bullet position - current x position)
angle = atan2(mouseY - py, mouseX - px);
// let's say you wanted all the bullets to go to the position (x=50, y=100), the code would be:
// angle = atan2(100 - py, 50 - px);
// this loop is to render and update every element of the bullets array.
for(let i = 0; i < bullets.length; i++) {
bullets[i].render();
bullets[i].update();
}
}
function mousePressed() {
// adding a bullet object to bullets array.
bullets.push(new Bullet(px, py, angle, 7));
}
function Bullet(x, y, angle, speed) {
// turning values px and py to vector to make calculations easier
this.position = createVector(x, y);
// learn more about fromAngle here: https://p5js.org/reference/#/p5.Vector/fromAngle
this.velocity = p5.Vector.fromAngle(angle).mult(speed);
this.render = function() {
// renders the bullet
push();
noStroke();
fill(255, 0, 0);
circle(this.position.x, this.position.y, 10);
pop();
}
this.update = function() {
// add bullet velocity to it's position to create the movement
this.position.add(this.velocity);
}
}