How to create a flower shape with ellipses within a class function? - javascript

I'm trying to make a mini game in which a flower (made up of ellipses) is moved by the mouse horizontally in order to catch rain droplets.
I'm struggling with several different issues and would love some help!
My first issue is that I originally placed the daisy (ellipses) inside the gameScreen function. I'm trying to place it inside of a class instead, because that will make it easier to target. I'm new to classes and can't even figure out how to place an ellipse within it, much less several. My attempt to put it into a class is called "daisy" in the code below. I can't get it to show up.
My second issue is making the game not end as soon as you miss one droplet. I would like it to end after missing 3, but can't figure it out what I need to change to do this.
And finally, my third issue would be making the color change to a darker and darker brown as the water droplets are missed.
Any help with any of these issues would be greatly appreciated! I've been trying to figure it out for days with no luck.
Original code snippet source shown below:
let screen = 0;
let score= 0;
let drop1;
let drop2;
let drop3;
function setup() {
createCanvas(600, 400);
drop1 = new rdrop1(70);
drop2 = new rdrop1(50);
drop3 = new rdrop1(25);
}
function draw() {
if(screen == 0){
startScreen();
}
else if(screen == 1){
gameScreen();
}
}
function startScreen(){
background(9, 143, 18);
fill(255);
textAlign(CENTER);
textSize(40);
text('water the daisy', width / 2, height / 2);
textSize(20);
text('click to start', width / 2, height / 2 + 40);
reset();
}
function gameScreen(){
background(9, 143, 18);
text("score = " + score, 50,25);
noStroke();
//flower
fill(240, 252, 243);
ellipseMode(CENTER);
// ellipse(mouseX+25,height-50,50,50);
ellipse(mouseX-25,height-50,50,50);
ellipse(mouseX,height-75,50,50);
ellipse(mouseX,height-25,50,50);
fill(235, 216, 52);
ellipse(mouseX,height-50,30,30);
drop1.update();
drop1.render();
drop2.update();
drop2.render();
drop3.update();
drop3.render();
if(drop1.y>height){
screen =2;
}
if(drop2.y>height){
screen =2;
}
if(drop3.y>height){
screen =2;
}
fill(255);
if(drop1.y>height-75 && drop1.x>mouseX-20 && drop1.x<mouseX+20){
score+= 1;
drop1.reset();
}
if(drop2.y>height-75 && drop2.x>mouseX-20 && drop2.x<mouseX+20){
score+= 1;
drop2.reset();
}
if(drop3.y>height-75 && drop3.x>mouseX-20 && drop3.x<mouseX+20){
score+= 1;
drop3.reset();
}
}
function mousePressed(){
if(screen==0){
screen=1;
}
else if(screen==2){
screen=0;
}
}
function reset(){
score=0;
drop1.speed=0.8;
drop1.y=-10;
drop2.speed=0.8;
drop2.y=-10;
drop3.speed=0.8;
drop3.y=-10;
}
class rdrop1{
constructor(size){
this.y = -10;
this.x = random(20,width-20);
this.size = size;
this.speed = 2;
}
update(){
this.y += this.speed
}
render(){
fill(7,179,223);
ellipse(this.x,this.y,this.size,this.size);
}
reset(){
this.y = -10
this.x = random(20,width-20)
this.speed+= 0.2
}
// reduceLife(){
// this.lifespan-=0.5
// }
}
class daisy{
constructor(xpos,ypos) {
this.x = mouseX+25;
this.y = height-50;
this.diameter = 50;
}
render(){
let c = map(rdrop1, 0, width, 0, 255);
if(this.lifespan===0){
fill (54, 32, 10)
}
fill (255, 253, 252)
ellipse(this.x,this.y,this.diameter);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js" crossorigin=""></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/addons/p5.sound.min.js" crossorigin=""></script>

I have updated your code a bit so it has the added features. The daisy class has a health variable which decreases whenever it misses a rain drop. Also, when this happens, its color gets darker.
I have added a gameSettings variable to hold all the data about the game. The advantages to this are: you can easily modify the attributes - for example to have difficulty levels. Also, it removes "magic" numbers - hard coded values in the main game code.
var gameSettings = {
canvasSize: {
width: 600,
height: 400
},
numRainDrops: 3,
initialSpeed: 2,
speedUp: 0.4,
daisyDiameter: 40,
daisyMaxHealth: 3,
minRainDropSize: 25,
maxRainDropSize: 75,
backgroundColor: "rgb(9, 143, 18)",
rainDropColor: "rgb(7, 179, 223)",
daisyColor: "rgb(235, 216, 52)",
textColor: "rgb(255, 255, 255)"
};
// Helper class to find intersections of circles.
// Can be improved for better accuracy
class boundingBox {
constructor(x, y, w, h) {
// Move x,y from center of circle to top,left of box
this.x = x - w / 2;
this.y = y - h / 2;
this.width = w;
this.height = h;
}
intersectsWith(other) {
return (Math.abs((this.x + this.width / 2) - (other.x + other.width / 2)) * 2 < (this.width + other.width)) &&
(Math.abs((this.y + this.height / 2) - (other.y + other.height / 2)) * 2 < (this.height + other.height));
}
}
class Game {
constructor() {
this.gameStatus = "start";
this.reset();
}
reset(width, height) {
// An array of raindrops - not hard-coded to 3
this.drops = [];
for (let i = 0; i < gameSettings.numRainDrops; i++) {
this.drops.push(new rainDrop(map(random(), 0, 1, gameSettings.minRainDropSize, gameSettings.maxRainDropSize)));
}
this.daisy = new daisy(gameSettings.daisyDiameter);
this.score = 0;
}
startGame() {
this.gameStatus = "running";
}
draw() {
if (this.gameStatus === "start") {
this.startScreen();
}
else if (this.gameStatus === "running") {
this.gameScreen();
}
}
startScreen() {
background(gameSettings.backgroundColor);
fill(gameSettings.textColor);
textAlign(CENTER);
textSize(40);
text('water the daisy', width / 2, height / 2);
textSize(20);
text('click to start', width / 2, height / 2 + 40);
}
// Main game loop
gameScreen() {
background(gameSettings.backgroundColor);
this.daisy.draw();
// Draw each raindrop and check if it hits the daisy
for (let drop of this.drops) {
drop.updateAndRender();
if (drop.boundingBox.intersectsWith(this.daisy.boundingBox)) {
this.score += 1;
drop.top();
}
else if (drop.isOffScreen()) {
drop.top();
this.daisy.health -= 1;
}
}
fill(gameSettings.textColor);
text("score = " + this.score, 50, 25);
}
isGameOver() {
// Check for game over - daisy health is 0
if (this.daisy.health <= 0) {
this.gameStatus = "stopped";
return true;
}
}
}
class rainDrop {
constructor(size) {
this.size = size;
this.y = -10;
this.x = random(20, width - 20);
this.speed = gameSettings.initialSpeed;
}
// Move back to top
top() {
this.y = -10;
this.x = random(20, width - 20);
this.speed += gameSettings.speedUp;
}
// Return this raindrops box
get boundingBox() {
return new boundingBox(this.x, this.y, this.size, this.size);
}
updateAndRender() {
this.y += this.speed;
fill(gameSettings.rainDropColor);
ellipse(this.x, this.y, this.size, this.size);
}
isOffScreen() {
return this.y >= height;
}
}
class daisy {
constructor(d) {
this.diameter = d;
this.center = {
x: mouseX + 25,
y: height - this.diameter
};
this.health = gameSettings.daisyMaxHealth;
}
get boundingBox() {
return new boundingBox(this.center.x, this.center.y, this.diameter, this.diameter);
}
draw() {
noStroke();
ellipseMode(CENTER);
// Petal color - the lower our health, the darker the petal
const color = map(this.health, 0, gameSettings.daisyMaxHealth, 0, 255);
fill(color, color, color);
// Draw petals
this.center.x = mouseX;
ellipse(this.center.x, this.center.y - this.diameter / 2, this.diameter, this.diameter);
ellipse(this.center.x, this.center.y + this.diameter / 2, this.diameter, this.diameter);
ellipse(this.center.x - this.diameter / 2, this.center.y, this.diameter, this.diameter);
ellipse(this.center.x + this.diameter / 2, this.center.y, this.diameter, this.diameter);
// Draw center
fill(gameSettings.daisyColor);
ellipse(this.center.x, this.center.y, this.diameter * .7, this.diameter * .7);
}
}
let game;
// Initialize
function setup() {
createCanvas(gameSettings.canvasSize.width, gameSettings.canvasSize.height);
game = new Game();
}
function draw() {
game.draw();
if (game.isGameOver()) {
game.reset();
}
}
function mousePressed() {
if (game.gameStatus !== "running") {
game.startGame();
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/addons/p5.sound.min.js"></script>

Related

Bouncing ball not staying the color assigned to it

I am writing a program for a ball to bounce off the edges of a box and change colors (much like the DVD logo). The problem is that once it changes colors, the fill function for the box overwrites the ball's color. I have tried conditionals and different function arrangements and asked my classmates for help, but none were helpful.
//
// Bounce1
// A simple bouncing ball - it has perfect bounces,
// it never slows down.
//These variables draw the canvas and the inner box
let canvasW = 900;
let canvasH = 700;
let innerborder = 100;
// These variables store the position, size, and speed.
let positionX = 300;
let positionY = 300;
let radius = 20;
let velocityX = 3;
let velocityY = 5;
//This variable helps with color change
let change = false;
function setup() {
createCanvas(canvasW, canvasH);
}
function draw() {
drawBackground();
moveBall();
drawBall();
}
function drawBackground(){
background(220);
innerRect();
}
function innerRect(){
fill (71, 71, 71);
rect (innerborder, 100, 700, 500);
}
function moveBall(){
// move the ball
positionX = positionX + velocityX;
positionY = positionY + velocityY;
const rightEdge = width - 100;
const leftEdge = 0 + 100;
const topEdge = 0 + 100;
const bottomEdge = height - 100;
// test to see if it hit an edge
if (positionX + radius > rightEdge) {
// hit the right edge
velocityX = velocityX * -1;
positionX = rightEdge - radius;
change = true;
if (change == true){
changeColor();
change = false
}
else if (change == false){
noFill();
}
}
else if (positionX - radius < leftEdge) {
// hit the left edge
velocityX = velocityX * -1;
positionX = leftEdge + radius;
change = true;
if (change == true){
changeColor();
change = false
}
else if (change == false){
noFill();
}
}
if (positionY + radius > bottomEdge) {
// hit the bottom edge
velocityY = velocityY * -1;
positionY = bottomEdge - radius;
change = true;
if (change == true){
changeColor();
change = false
}
else if (change == false){
noFill();
}
}
else if (positionY - radius < topEdge) {
// hit the top edge
velocityY = velocityY * -1;
positionY = topEdge + radius;
change = true;
if (change == true){
changeColor();
change = false
}
else if (change == false){
noFill();
}
}
}
function drawBall(){
// draw the ball
ellipse(positionX, positionY, radius * 2, radius * 2);
}
function changeColor(){
//Colors
let r = random(0, 255);
let g = random(0, 255);
let b = random(0, 255);
fill (r, g, b);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.js"></script>
Try storing the current ball colors in variables so you can re-call fill(ballRed, ballGreen, ballBlue) just before redrawing the ball. changed isn't necessary and doesn't really help with the fact that innerRect()'s fill() will override any other fill() calls that happened on previous frames.
const canvasW = 900;
const canvasH = 700;
const innerborder = 100;
let positionX = 300;
let positionY = 300;
let radius = 20;
let velocityX = 3;
let velocityY = 5;
let r, g, b;
let rightEdge;
let leftEdge;
let topEdge;
let bottomEdge;
function setup() {
createCanvas(canvasW, canvasH);
rightEdge = width - 100;
leftEdge = 0 + 100;
topEdge = 0 + 100;
bottomEdge = height - 100;
changeColor();
}
function draw() {
drawBackground();
moveBall();
if (checkCollision()) {
resolveCollision();
changeColor();
}
drawBall();
}
function drawBackground() {
background(220);
innerRect();
}
function innerRect() {
fill(71, 71, 71);
rect(innerborder, 100, 700, 500);
}
function moveBall() {
positionX = positionX + velocityX;
positionY = positionY + velocityY;
}
const checkCollision = () =>
positionX + radius > rightEdge ||
positionX - radius < leftEdge ||
positionY + radius > bottomEdge ||
positionY - radius < topEdge
;
const resolveCollision = () => {
if (positionX + radius > rightEdge) {
// hit the right edge
velocityX = velocityX * -1;
positionX = rightEdge - radius;
} else if (positionX - radius < leftEdge) {
// hit the left edge
velocityX = velocityX * -1;
positionX = leftEdge + radius;
}
if (positionY + radius > bottomEdge) {
// hit the bottom edge
velocityY = velocityY * -1;
positionY = bottomEdge - radius;
} else if (positionY - radius < topEdge) {
// hit the top edge
velocityY = velocityY * -1;
positionY = topEdge + radius;
}
};
function drawBall() {
fill(r, g, b);
ellipse(positionX, positionY, radius * 2, radius * 2);
}
function changeColor() {
r = random(0, 255);
g = random(0, 255);
b = random(0, 255);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.5.0/p5.js"></script>
After that, you might want to consider refactoring the code to put all of the loose variables and functions associated with a ball into an object. Something like
const ball = {
x: 42,
y: 42,
r: 0,
b: 0,
g: 0,
radius: 20,
vx: 3,
vy: 5,
changeColor() {
// ...
},
draw() {
// ...
},
// ...
};
and use it with ball.changeColor(). This logical grouping makes the code easier to read and extend.

p5js Moving Circles Collisions Detection

I have made a simple sketch where 4 circles are moving at a given speed. I want to change the fill color when any of the circles touches another circle.
I think the problem is that I am initializing the x and y values for ellipse in my constructor object which I need to update as the circle moves, but I am not sure how to do that.
// Declare objects
let bubble1;
let bubble2;
let bubble3;
let bubble4;
var centDistance;
function setup() {
createCanvas(windowWidth, windowHeight);
ellipseMode(CENTER);
// Create objects
bubble1 = new Bubble(50, 0, 2);
bubble2 = new Bubble(50, 2, 0);
bubble3 = new Bubble(50, -2, 0);
bubble4 = new Bubble(50, 0, -2);
}
function draw() {
background(0);
bubble1.display();
bubble2.display();
bubble1.move();
bubble2.move();
bubble3.display();
bubble3.move();
bubble4.display();
bubble4.move();
var d = dist(bubble1.x, bubble1.y, bubble2.x, bubble2.y);
if (d < bubble1.r + bubble2.r) {
bubble1.changeCol();
bubble2.changeCol();
}
}
class Bubble {
constructor(r, xSpeed, ySpeed) {
this.x = width / 2;
this.y = height / 2;
this.r = r;
this.xSpeed = xSpeed;
this.ySpeed = ySpeed;
this.fillColor = color(255);
this.move = function() {
if (this.x > width / 2 + 200 || this.x < width / 2 - 200) {
this.xSpeed = -this.xSpeed;
}
if (this.y > height / 2 + 200 || this.y < height / 2 - 200) {
this.ySpeed = -this.ySpeed;
}
this.x += this.xSpeed;
this.y += this.ySpeed;
}
this.display = function() {
fill(this.fillColor);
stroke(255);
ellipse(this.x, this.y, 2 * this.r);
}
this.changeCol = function() {
this.fillColor = color(0);
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.1/p5.js"></script>
The problem is that when the animation starts both circles are colliding, bubble1 and bubble2 in this example.
then you change the color to black inside your changeCol function and they both turn black and then stay that way indefinitely.
Your code is working the problem is that this.fillColor will not be re-initialized every re-render since you've instanciated your objects inside the setup function, so you have to re-paint the circles when they're not touching one another.
if (d < bubble1.r+bubble2.r) {
bubble1.changeCol(255);
bubble2.changeCol(255);
} else {
bubble1.changeCol(0);
bubble2.changeCol(0);
}
this.changeCol = function (col) {
this.fillColor = color(col);
}

P5.js how to do 8 directional lerp color/color change?

A last issue i have in this code is that i am not sure how to create color change effect as 8 directional.
I can only map a mouseX to make it lerpColor horizontally or vertically .
But how do i make it work through moving both mouseX and mouseY?
I had it in shift_Color method within the class. I tried to state that within a certain dist(), lerpColor. But now it only showing black color rather than the changing color effect.
let cubes = [];
function setup() {
createCanvas(windowWidth, windowHeight, WEBGL);
backCol = color(243, 243, 243);
//background(backCol);
for (let i = 0; i < 10; i++) {
for (let j = 0; j < 10; j++) {
let xPos = map(i, 0, 9, 50, width - 50);
let yPos = map(j, 0, 9, 50, height - 50);
cubes.push(new Cubes(xPos, yPos));
}
}
}
function draw() {
background(backCol);
noFill();
for (let a = 0; a < cubes.length; a++) {
cubes[a].update();
}
}
class Cubes {
constructor(x, y) {
this.x = x;
this.y = y;
this.size = 30;
this.stroke = 70;
this.gap = 110
this.shift1 = color(96);
this.shift2 = color(244);
}
update() {
this.shape();
this.shift_Color();
}
shape() {
push();
stroke(this.stroke);
//fill(this.shift1);
this.shift_Color();
translate(this.x - width / 2, this.y - height / 2, 0);
this.magnetic()
box(this.size);
pop();
}
shift_Color() {
let distance = dist(mouseX, mouseY, this.x, this.y);
if (distance < this.gap) {
this.shift1 = color(96);
this.shift2 = color(244);
this.shiftX = map(mouseX - width/2,this.gap,distance,0,1.0);
this.change = lerpColor(this.shift1, this.shift2, this.shiftX);
fill(this.change);
} else {
fill(this.shift1);
}
}
magnetic() {
let distance = dist(mouseX, mouseY, this.x, this.y);
if (distance < this.gap) {
this.attract = atan2(mouseY - this.y, mouseX - this.x);
rotateX(this.attract);
rotateY(this.attract);
} else {
rotateX(millis() / 1000);
rotateY(millis() / 1000);
}
}
}
If I understood your question properly, there are two problems in your code.
The first is the fact that because you are trying to map the distance between mouse and the cube to number between 0 and 1, you should write lerpColor(this.shift2, this.shift1, this.shiftX) instead of lerpColor(this.shift1, this.shift2, this.shiftX), since this.shift2 is the lighter color and will be the inner color.
Another problem is when mapping the change variable, change should be calculated based on the distance between mouse and the cube (which is the distance variable), not mouseX or mouseY. Solution is to simply do map(distance, 0, this.gap, 0, 1);.
let cubes = [];
function setup() {
createCanvas(windowWidth, windowHeight, WEBGL);
backCol = color(243, 243, 243);
for (let i = 0; i < 10; i++) {
for (let j = 0; j < 10; j++) {
let xPos = map(i, 0, 9, 50, width - 50);
let yPos = map(j, 0, 9, 50, height - 50);
cubes.push(new Cubes(xPos, yPos));
}
}
}
function draw() {
background(backCol);
noFill();
for (let cube of cubes) {
cube.update();
}
}
class Cubes {
constructor(x, y) {
this.x = x;
this.y = y;
this.size = 30;
this.stroke = 70;
this.gap = 110
this.shift1 = color(96);
this.shift2 = color(244);
}
update() {
this.shape();
this.shift_Color();
}
shape() {
push();
stroke(this.stroke);
//fill(this.shift1);
this.shift_Color();
translate(this.x - width / 2, this.y - height / 2, 0);
this.magnetic()
box(this.size);
pop();
}
shift_Color() {
let distance = dist(mouseX, mouseY, this.x, this.y);
if (distance < this.gap) {
this.shiftX = map(distance, 0, this.gap, 0, 1);
// this.shiftX = map(mouseX - width/2,this.gap,distance,0,1.0);
this.change = lerpColor(this.shift2, this.shift1, this.shiftX);
// this.change = lerpColor(this.shift1, this.shift2, this.shiftX);
fill(this.change);
} else {
fill(this.shift1);
}
}
magnetic() {
let distance = dist(mouseX, mouseY, this.x, this.y);
if (distance < this.gap) {
this.attract = atan2(mouseY - this.y, mouseX - this.x);
rotateX(this.attract);
rotateY(this.attract);
} else {
rotateX(millis() / 1000);
rotateY(millis() / 1000);
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>
I also modified some of your code. Like the line
this.shift1 = color(96);
this.shift2 = color(244);
which is not needed currently since neither of these variable changes during execution.

I'm attempting to write a program where the ball ignores hitting a green obstacle but ends the game when a red obstacle indicates game over

I'm attempting to write a JavaScript program where the ball ignores hitting a green obstacle but ends the game when a red obstacle indicates game over. However in my code the game ends when the ball hits an obstacle of any color.
My definition of the obstacle is:
function Obstacle(x, size, horizon, color) {
this.x = x;
this.y = horizon - size;
this.size = size;
this.color = color;
this.onScreen = true;
}
/**
* handle x and onScreen values
*/
Obstacle.prototype.update = function(speed) {
/* check if offscreen */
this.onScreen = (this.x > -this.size);
/* movement */
this.x -= speed;
};
Obstacle.prototype.draw = function() {
fill(this.color);
stroke(255);
strokeWeight(2);
rect(this.x, this.y, this.size, this.size);
};
Obstacle.prototype.hits = function(ball) {
var halfSize = this.size / 2;
var minimumDistance = halfSize + (ball.radius); // closest before collision
/* find center coordinates */
var xCenter = this.x + halfSize;
var yCenter = this.y + halfSize;
var distance = dist(xCenter, yCenter, ball.x, ball.y); // calculate distance from centers
return (distance < minimumDistance); // return result
};
This is the code for the game:
function setup() {
createCanvas(600, 200);
textAlign(CENTER);
horizon = height - 40;
score = 0;
obstacleSpeed = 6;
var size = 20;
ball = new bol(size * 2, height - horizon, size);
textSize(20);
}
function draw() {
background(51);
drawHUD();
handleLevel(frameCount);
ball.update(horizon);
handleObstacles();
//handlepowerups();
}
/**
* draws horizon & score
*/
function drawHUD() {
/* draw horizon */
stroke(255);
strokeWeight(2);
line(0, horizon, width, horizon);
/* draw score */
noStroke();
text("Score: " + score, width / 2, 30);
ball.draw();
}
/**
* updates, draws, and cleans out the obstacles
*/
function handleObstacles() {
for (var i = obstacles.length - 1; i >= 0; i--) {
obstacles[i].update(obstacleSpeed);
obstacles[i].draw();
if (obstacles[i].hits(ball)) // if there's a collision
{
if (obstacles[i].color = color(225, 0, 0))
endGame();
else
obstacles[i].color = color(0, 0, 225)
}
if (!obstacles[i].onScreen) // if it's no longer showing
obstacles.splice(i, 1); // delete from array
}
}
/**
* speeds game up, pushes new obstacles, & handles score
*/
function handleLevel(n) {
if (n % 100 === 0) { // every 0.5 seconds
var n = noise(n);
if (n > 0.5)
newObstacle(n); // push new obstacle
if (n % 120 === 0) // every 2 seconds
obstacleSpeed *= 1.05; // speed up
}
score++;
}
/**
* pushes random obstacle
*/
function newObstacle(n) {
var col1 = color(225, 0, 0);
var col2 = color(0, 225, 0);
var size = random(25) + 20;
var obs = new Obstacle(width + size, size, horizon, col2);
var obs2 = new Obstacle(width + size, size, horizon, col1);
var cases = random(1);
if (cases < 0.5)
obstacles.push(obs);
else
obstacles.push(obs2)
}
function keyPressed() {
if ((keyCode === UP_ARROW || keyCode === 32) && ball.onGround) // jump if possible
ball.jump();
boingaudio.play()
}
function endGame() {
noLoop();
noStroke();
textSize(40);
text("GAME OVER", width / 2, height / 2);
if (highscore !== null) {
if (score > highscore) {
localStorage.setItem("highscore", score);
}
} else {
localStorage.setItem("highscore", score);
}
textSize(20);
text("Highscore: " + highscore, width / 2, height / 2 + 20);
gameoveraudio.play()
}
I don't understand why the ball keeps ending game for no matter what colored ball appears. Can you help me figure out what's wrong?
You seem to be assigning a value to obstacles[i].color rather than testing it:
if (obstacles[i].color = color(225, 0, 0))
endGame();
else
obstacles[i].color = color(0, 0, 225)
This should probably read:
if (obstacles[i].color == color(225, 0, 0))
endGame();
Without your else, which seemed to serve no purpose.

p5.js Collision Detection

I'm trying to use p5.js's p5.collide2D library to execute some actions. I have a main pulsing module that pulses size-wise to music playing in my sketch, and then as it hits certain shapes I have displaying, I want it to reference the different functions I've set up to transform the main module visually.
Currently in this sketch I'm trying to get the Circle2 function to draw when touchX + touchY collides with the maroon circle. I thought I was using the library correctly, but maybe not. Any help would be great. Thanks!
var circles = [];
var squares = [];
var sizeProportion = 0.2;
//additional shapes
var r = 0;
var velocity = 1;
var fillColor = color(0, 0, 0);
var hit = false;
var startTime;
var waitTime = 3000;
var drawCircles;
var drawSquares;
function preload() {
sound = loadSound('assets/findingnemoegg.mp3');
}
function setup() {
createCanvas(windowWidth, windowHeight);
amplitude = new p5.Amplitude();
sound.loop();
sound.play();
startTime = millis();
}
function draw() {
background(255);
// other shapes + information
r = r + velocity;
if ((r > 256) || (r < 0)) {
velocity = velocity * -1;
}
noStroke();
fill(144, 12, 63, r);
ellipse(100, 100, 80, 80);
// drawing circles
circles.push(new Circle1(touchX, touchY));
for (var i = 0; i < circles.length; i++) {
circles[i].display();
if (circles[i].strokeOpacity <= 0) { // Remove if faded out.
circles.splice(i, 1); // remove
}
}
//collisions
if (pointTouchcircle2(touchX, 100, 100)) { // <- collision detection
//call upon Circle2 function and have the main module draw that
} else {
//stay the same.
}
}
//starting circles
function Circle1(x, y) {
this.x = x;
this.y = y;
this.size = 0;
this.age = 0;
this.fillOpacity = 20
this.strokeOpacity = 30
this.display = function() {
var level = amplitude.getLevel();
this.age++;
if (this.age > 500) {
this.fillOpacity -= 1;
this.strokeOpacity -= 1;
}
var newSize = map(level, 0, 1, 20, 900);
this.size = this.size + (sizeProportion * (newSize - this.size));
strokeWeight(10);
stroke(152, 251, 152, this.strokeOpacity);
fill(23, 236, 236, this.fillOpacity);
ellipse(this.x, this.y, this.size);
}
}
//maroon circles
function Circle2(x, y) {
this.x = x;
this.y = y;
this.size = 0;
this.age = 0;
this.fillOpacity = 20
this.strokeOpacity = 30
this.display = function() {
var level = amplitude.getLevel();
this.age++;
if (this.age > 500) {
this.fillOpacity -= 1;
this.strokeOpacity -= 1;
}
var newSize = map(level, 0, 1, 20, 900);
this.size = this.size + (sizeProportion * (newSize - this.size));
strokeWeight(10);
stroke(173, 212, 92, this.strokeOpacity);
fill(144, 12, 63, this.fillOpacity);
ellipse(this.x, this.y, this.size);
}
}
//collision functions
function pointTouchcircle2(touch, x, y) {
if (hit = collidePointCircle(touchX,touchY,100,100,50)) {
return true
} else {
return false
}
}

Categories

Resources