Unknown Error in P5.js - javascript

I am having an issue finding the error in my code. I am making my own version of space invaders for a school project. P5 isn't showing any errors, but when I do a test run of the code, all I get is a white screen. I need an extra set of eyes for this. Any help is appreciated. Thanks!!
//initializes bullets
var bullets = {
x: new Array(),
y: new Array(),
shot: new Array()
}
//initializes the ship
var ship = {
x: 625,
y: 475,
photo: loadImage("download.png")
}
function setup() {
createCanvas(1350,650);
//bullet1
append(bullets.x, ship.x);
append(bullets.y, ship.y);
append(bullets.shot, false);
//bullet2
append(bullets.x, ship.x);
append(bullets.y, ship.y);
append(bullets.shot, false);
//bullet3
append(bullets.x, ship.x);
append(bullets.y, ship.y);
append(bullets.shot, false);
}
//Controls
function updateShip()
{
//Right movement
if (keyIsDown(RIGHT_ARROW)) {
ship.x = ship.x+ 10;
if (ship.x >= 1350) {
ship.x = ship.x - 11;
}
}
//Left movement
if (keyIsDown(LEFT_ARROW)) {
ship.x = ship.x - 10;
if (ship.x <= 0) {
ship.x = ship.x + 11;
}
}
//Up movement
if (keyIsDown(UP_ARROW)) {
ship.y = ship.y - 10;
if (ship.y <= 350) {
ship.y = ship.y + 11;
}
}
//Down movement
if (keyIsDown(DOWN_ARROW)) {
ship.y = ship.y + 10;
if (ship.y >= 580) {
ship.y = ship.y - 11;
}
}
}
function drawShip()
{
ship.photo.resize(75,75);
image(ship.photo,ship.x-ship.photo.width/2,ship.y+ship.photo.height/2);
}
//Drawing the bullets
function drawBullets() {
fill(255);
rect(bullets.x[0],bullets.y[0], 5, 10);
rect(bullets.x[1],bullets.y[1], 5, 10);
rect(bullets.x[2],bullets.y[2], 5, 10);
}
//Controls the bullet movement
function updateBullets() {
bullets.y[0] = bullets.y[0] + 10;
}
//Checks if bullet is shot
function checkShoot() {
if (keyIsPressed && keyCode === 32) {
bullets.y[0] = ship.y;
}
}
function draw() {
background(0);
updateShip();
drawShip();
checkShoot();
updateBullets();
drawBullets();
}

You should move loadImage() function into your sketch's setup() function.
Like this
var ship;
function setup() {
createCanvas(1350,650);
ship = {
x: 625,
y: 475,
photo: loadImage("download.png")
}
//something
}

Related

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

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>

P5.js game crashes due to TypeError for a missing element in an array

OK, so I run into this problem where my program regularly crashes mid-game due to a TypeError: Uncaught TypeError: bullets[i] is undefined
The error occurs in the function where I check for every variable in the bullets and the enemies array if there is a collision.
This is the Source Code of this small school project I created, and I've been trying to troubleshoot this particular bug for hours at a time now. If anyone were able to help me that would be amazing as I can't quite grasp what the problem could be other than their occurring a collision when an element has already been spliced. But since the draw() function in P5.js runs 60 times per second that shouldn't really happen as regularly as it does, so I don't understand how this even can be an issue.
function setup() {
createCanvas(displayWidth - 20, displayHeight - 20);
angleMode(DEGREES);
rectMode(CENTER);
ellipseMode(CENTER);
playerX = width / 2;
playerY = height / 2;
}
let playerX = 0;
let playerY = 0;
let angle = 0;
let timer = 120;
let time = 0;
let v = 2;
let cooldown = 20;
let color = 50;
let hit = 0;
var bullets = [];
var enemies_easy = [];
var enemies_hard = [];
var score = 0;
var highscore = 0;
var gameover = false;
var gamestarted = false;
var nexthard = 5;
var currentenemy = 0;
function draw() {
if (!gamestarted) {
push();
textAlign(CENTER);
background('black');
translate(displayWidth / 2, displayHeight / 2);
textSize(width / 50);
fill('white');
text('Welcome!', 0, -100);
text('Controls:', 0, 0);
text('Fullscreen: F Moving: W, A, S, D Restart: R Shooting: Left Mouse Button Start: Space Bar', 0, 100);
pop();
if (keyIsDown(32)) {
bullets = [];
gamestarted = true;
}
} else {
if (!gameover) {
//calculates shot enemies_easy
bulletcollision();
//shoots if weapon cooldown is expired
background('black');
cooldown--;
activategun();
//draw hero
angle = atan2(mouseY - playerY, mouseX - playerX) + 90;
push();
fill('blue');
translate(playerX, playerY);
rotate(angle);
ellipse(0, 0, 40, 40);
//draw gun
fill('grey');
rect(0, 0 - 25, 10, 20);
pop();
//move hero
move();
//creates enemies with increasing difficulty
time++;
difficulty();
spawnenemy_easy();
spawnenemy_hard();
//shows score on screen
showscore();
//draw crosshair
noCursor();
push();
fill('white');
stroke('white');
line(mouseX, mouseY, mouseX + 20, mouseY);
line(mouseX, mouseY, mouseX - 20, mouseY);
line(mouseX, mouseY, mouseX, mouseY + 20);
line(mouseX, mouseY, mouseX, mouseY - 20);
pop();
//checks for game over
playercollision();
} else {
if (keyIsDown(82)) {
bullets = [];
enemies_easy = [];
enemies_hard = [];
timer = 120;
time = 0;
cooldown = 20;
score = 0;
playerX = width / 2;
playerY = height / 2;
v = 2;
gameover = false;
}
}
}
}
class bullet {
constructor() {
this.x = playerX;
this.y = playerY;
this.angle = createVector(mouseX - playerX, mouseY - playerY);
this.angle.normalize();
}
drawbullet() {
push();
fill('white');
ellipse(this.x, this.y, 10, 10);
pop();
this.y = this.y + 10 * this.angle.y;
this.x = this.x + 10 * this.angle.x;
}
}
class enemy_easy {
constructor() {
this.x = random(-1000, width + 1000);
if (this.x > width || this.x < 0) {
if (this.x > width) {
this.x = width;
this.y = random(0, height + 1);
}
if (this.x < 0) {
this.x = 0;
this.y = random(0, height + 1);
} else {}
} else {
let i = floor(random(0, 2));
this.y = i * height;
}
}
drawenemy_easy() {
push();
this.angle = createVector(this.x - playerX, this.y - playerY);
this.angle.normalize();
fill('red');
ellipse(this.x, this.y, 30, 30);
rotate(angle);
pop();
this.x = this.x - v * this.angle.x; // * random(0, 5);
this.y = this.y - v * this.angle.y; // * random(0, 5);
}
}
class enemy_hard {
constructor() {
this.x = random(-1000, width + 1000);
if (this.x > width || this.x < 0) {
if (this.x > width) {
this.x = width;
this.y = random(0, height + 1);
}
if (this.x < 0) {
this.x = 0;
this.y = random(0, height + 1);
} else {}
} else {
let i = floor(random(0, 2));
this.y = i * height;
}
}
drawenemy_hard() {
push();
this.angle = createVector(this.x - playerX, this.y - playerY);
this.angle.normalize();
fill('purple');
ellipse(this.x, this.y, 30, 30);
rotate(angle);
pop();
this.x = this.x - v * this.angle.x; // * random(0, 5);
this.y = this.y - v * this.angle.y; // * random(0, 5);
}
}
function keyPressed() {
//fullscreen Taste F: https://www.geeksforgeeks.org/p5-js-fullscreen-function/
if (keyCode === 70) {
let fs = fullscreen();
fullscreen(!fs);
}
}
function move() {
if (keyIsDown(83) && playerY <= height - 22) {
playerY = playerY + 4;
}
if (keyIsDown(87) && playerY >= 22) {
playerY = playerY - 4;
}
if (keyIsDown(68) && playerX <= width - 22) {
playerX = playerX + 4;
}
if (keyIsDown(65) && playerX >= 22) {
playerX = playerX - 4;
}
}
function activategun() {
for (var i = 0; i < bullets.length; i++) {
bullets[i].drawbullet();
if (bullets[i].x <= 0 || bullets[i].y <= 0 || bullets[i].x >= width || bullets[i].y >= height) {
bullets.splice(i, 1);
}
}
}
function mousePressed() {
if (cooldown < 0) {
bullets.push(new bullet());
cooldown = 20;
}
}
function spawnenemy_easy() {
for (var i = 0; i < enemies_easy.length; i++) {
enemies_easy[i].drawenemy_easy();
}
}
function spawnenemy_hard() {
for (var i = 0; i < enemies_hard.length; i++) {
enemies_hard[i].drawenemy_hard();
}
}
function newenemy() {
if (currentenemy < nexthard) {
enemies_easy.push(new enemy_easy());
currentenemy++;
} else {
enemies_hard.push(new enemy_hard());
currentenemy = 0;
nexthard = random(2, 6);
}
}
function bulletcollision() {
for (var i = 0; i < bullets.length; i++) {
for (var e = 0; e < enemies_easy.length; e++) {
var distance = createVector(bullets[i].x - enemies_easy[e].x, bullets[i].y - enemies_easy[e].y);
if (distance.mag() <= 18) {
bullets.splice(i, 1);
enemies_easy.splice(e, 1);
score++;
if (score > highscore) {
highscore++;
}
}
}
for (var e = 0; e < enemies_hard.length; e++) {
var distance = createVector(bullets[i].x - enemies_hard[e].x, bullets[i].y - enemies_hard[e].y);
if (distance.mag() <= 18) {
bullets.splice(i, 1);
hit++;
if (hit == 2) {
enemies_hard.splice(e, 1);
score++;
if (score > highscore) {
highscore++;
}
hit = 0;
}
}
}
}
}
function playercollision() {
for (var i = 0; i < enemies_easy.length; i++) {
var distance = createVector(enemies_easy[i].x - playerX, enemies_easy[i].y - playerY);
if (distance.mag() <= 25) {
push();
background(abs(255 * sin(random(0, 255))), 255 * sin(random(0, 255)), 255 * sin(random(0, 255)));
fill('white');
textAlign(CENTER);
textSize(width / 40);
translate(width / 2, height / 2);
text("Game Over!", 0, -100);
text("Score: " + score, 0, 0);
text("High Score: " + highscore, 0, 100);
pop();
return gameover = true;
}
}
for (var i = 0; i < enemies_hard.length; i++) {
var distance = createVector(enemies_hard[i].x - playerX, enemies_hard[i].y - playerY);
if (distance.mag() <= 25) {
push();
background(abs(255 * sin(random(0, 255))), 255 * sin(random(0, 255)), 255 * sin(random(0, 255)));
fill('white');
textAlign(CENTER);
textSize(width / 40);
translate(width / 2, height / 2);
text("Game Over!", 0, -100);
text("Score: " + score, 0, 0);
text("High Score: " + highscore, 0, 100);
pop();
return gameover = true;
}
}
}
function difficulty() {
if (time >= timer) {
newenemy();
time = 0;
timer = timer * 0.99;
v = v * 1.02;
}
}
function showscore() {
push();
fill('white');
textSize(width / 55);
textAlign(CENTER);
text('Score: ' + score, 100, 100);
pop();
}
Does anyone know how I could fix this issue or if I even can?
Any help is appreciated!
The problem is that you are removing bullets from the array as you iterate through the array. Use while-loop instead of the for-loop:
function bulletcollision() {
let i = 0;
while (i < bullets.length) {
let bullet_hit = false;
for (var e = 0; e < enemies_easy.length; e++) {
var distance = createVector(bullets[i].x - enemies_easy[e].x, bullets[i].y - enemies_easy[e].y);
if (distance.mag() <= 18) {
bullet_hit = true;
destroy_enemy(enemies_easy, e);
}
}
for (var e = 0; e < enemies_hard.length; e++) {
var distance = createVector(bullets[i].x - enemies_hard[e].x, bullets[i].y - enemies_hard[e].y);
if (distance.mag() <= 18) {
bullet_hit = true;
hit++;
if (hit == 2) {
destroy_enemy(enemies_hard, e);
hit = 0;
}
}
}
if (bullet_hit) {
bullets.splice(i, 1);
} else {
i ++;
}
}
}
function destroy_enemy(enemies, e) {
enemies.splice(e, 1);
score++;
highscore = Math.max(highscore, score);
}
See also Looping through array and removing items, without breaking for loop.

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.

Unexpected "Illegal return statement"

So i have my code here:
var canvas = document.getElementById('c');
var ctx = c.getContext('2d');
var player = {
x: 0,
y: 0,
width: 20,
height: 20,
speed: 3,
velX: 0,
velY: 0,
jumping: false,
grounded: false,
gravity: 0.35,
friction: 0,
glitchCooldown: 0,
keys: []
};
var walls = [];
walls.push({
x: 50,
y: 230,
width: 20,
height: 20
})
walls.push({
x: 150,
y: 230,
width: 20,
height: 20
})
player.y = canvas.height - player.width;
document.body.addEventListener("keydown", function(e) {
player.keys[e.keyCode] = true;
});
document.body.addEventListener("keyup", function(e) {
player.keys[e.keyCode] = false;
});
function update() {
if (player.keys[68]) {
if (player.velX < player.speed) {
player.velX++;
}
};
if (player.keys[65]) {
if (player.velX > -player.speed) {
player.velX--;
}
};
if (player.keys[87]) {
if (!player.jumping) {
player.jumping = true;
player.grounded = false;
player.velY = -player.speed*2;
}
};
if (player.keys[74]) {
glitch('backward');
};
if (player.keys[75]) {
glitch('down')
};
if (player.keys[76]) {
glitch('forward')
};
player.velY += player.gravity;
player.velX *= player.friction;
player.x += player.velX;
player.y += player.velY;
ctx.clearRect(0, 0, canvas.width, canvas.height);
player.grounded = false;
for (var i = 0; i < walls.length; i++) {
rect('black', walls[i].x, walls[i].y, walls[i].width, walls[i].height);
var dir = colCheck(player, walls[i]);
if (dir === "l" || dir === "r") {
player.velX = 0;
player.jumping = false;
} else if (dir === "b") {
player.grounded = true;
player.jumping = false;
} else if (dir === "t") {
player.velY *= -1;
}
}
if (player.grounded){
player.velY = 0;
}
if (player.glitchCooldown <= 0) {
player.glitchCooldown = 0;
}
player.glitchCooldown--;
rect('black', player.x, player.y, player.width, player.height);
requestAnimationFrame(update);
};
requestAnimationFrame(update)
function rect(color, x, y, width, height) {
ctx.fillStyle = color;
ctx.fillRect(x, y, width, height);
}
function glitch(x) {
if (player.glitchCooldown <= 0) {
setTimeout(function(){player.width = 0}, 200);
setTimeout(function(){player.width = 20}, 220);
setTimeout(function(){player.width = 0}, 400);
setTimeout(function(){player.width = 20}, 420);
setTimeout(function(){player.width = 0}, 500);
setTimeout(function(){player.width = 20}, 510);
setTimeout(function(){player.width = 0}, 530);
setTimeout(function(){player.width = 20}, 550);
if (x == 'forward'){setTimeout(function(){player.x += 20;}, 700)};
if (x == 'backward'){setTimeout(function(){player.x -= 20;}, 700)};
if (x == 'down'){setTimeout(function(){player.y += 20;}, 700)};
setTimeout(function(){player.glitchCooldown = 120}, 700);
}
}
function colCheck(shapeA, shapeB) {
// get the vectors to check against
var vX = (shapeA.x + (shapeA.width / 2)) - (shapeB.x + (shapeB.width / 2)),
vY = (shapeA.y + (shapeA.height / 2)) - (shapeB.y + (shapeB.height / 2)),
// add the half widths and half heights of the objects
hWidths = (shapeA.width / 2) + (shapeB.width / 2),
hHeights = (shapeA.height / 2) + (shapeB.height / 2),
colDir = 'l';
// if the x and y vector are less than the half width or half height, they we must be inside the object, causing a collision
if (Math.abs(vX) < hWidths && Math.abs(vY) < hHeights) { // figures out on which side we are colliding (top, bottom, left, or right) var oX = hWidths - Math.abs(vX), oY = hHeights - Math.abs(vY); if (oX >= oY) {
if (vY > 0) {
colDir = "t";
shapeA.y += oY;
} else {
colDir = "b";
shapeA.y -= oY;
}
} else {
if (vX > 0) {
colDir = "l";
shapeA.x += oX;
} else {
colDir = "r";
shapeA.x -= oX;
}
}
}
return colDir;
}
function random() {
var x = Math.floor((Math.random() * 10) + 1);
return x;
}
<html>
<head>
<title>CoRRupTed</title>
<link rel="stylesheet" href="design.css">
</head>
<body>
<canvas height='250' width='1350' style='border: 1px solid black' id='c'>Your browser do not support the <canvas> tag. Please update your browser.</canvas>
<script src='main.js'></script>
</body>
</html>
As you can see, my colCheck function is not working properly. It suppose to return colDir as 'l', 'r', 'b' or 't'. Buut the error says "Illegal resturn statement", so I think that colCheck is returning colDir as null. Therefore, in my code, I already write var col = colCheck(player, walls[i]), but it is still not working properly. Any ideas?
This is because you are not consistently styling your code.
The error means you have mismatching opening and closing braces.
the line
if (Math.abs(vX) < hWidths && Math.abs(vY) < hHeights) { // figures out on which side we are colliding (top, bottom, left, or right) var oX = hWidths - Math.abs(vX), oY = hHeights - Math.abs(vY); if (oX >= oY) {
should be. Comments within /* */ have been added by me.
/* DONT make comment run past right edge of screen put them in the line above */
// figures out on which side we are colliding (top, bottom, left, or right)
if (Math.abs(vX) < hWidths && Math.abs(vY) < hHeights) {
/* DONT use , to separate variable declarations */
const oX = hWidths - Math.abs(vX); /*Use consts for vars that don't change*/
const oY = hHeights - Math.abs(vY);
if (oX >= oY) {

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