xxxxxxxxxx
137
let aPressed = false;
let spacePressed = false;
let dPressed = false;
let lvl = 1
let lvlplatX = []
let lvlplatY = []
var lvl1platX = [15, 75, 115, 115, 275, 350 ]
var lvl1platY = [350, 300, 225, 160, 140, 170]
var lvl2platX = [15, 50, 80, 125, 180, 225, 255, 300, 350]
var lvl2platY = [350, 300, 200, 160, 225, 250, 300, 200, 100]
var grav = 0.6;
var ground = 375;
var platforms = [];
function setup() {
createCanvas(400, 400);
document.addEventListener("keydown", keyDownChecker, false);
document.addEventListener("keyup", keyUpChecker, false);
if (lvl == 1){
lvlplatX = lvl1platX.slice(0)
lvlplatY = lvl1platY.slice(0)
}
if (lvl == 2){
lvlplatX = lvl2platX.slice(0)
lvlplatY = lvl2platY.slice(0)
}
for (let i = 0; i < lvlplatX.length; i++) {
let newPlatform = new Platform(color(255, 0, 0), lvlplatX[i], lvlplatY[i], 50, 8);
platforms.push(newPlatform);
}
}
function draw() {
frameRate(100)
background(220);
if (spacePressed && jumper.onPlatform == true) {
jumper.deltaY = -10;
jumper.onPlatform = false;
}
if (aPressed == true){
jumper.x -= jumper.sideSpeed
}
if (dPressed == true){
jumper.x += jumper.sideSpeed
}
if (!jumper.onPlatform){
jumper.deltaY += grav;
jumper.y += jumper.deltaY;
}
else{
jumper.deltaY = 0
}
let hasJumperCollided = false;
let jumperCollisionPoint = jumper.y + jumper.size / 2;
for (let i = 0; i < platforms.length; i++) {
if (jumper.x + jumper.size / 2 > platforms[i].x && jumper.x - jumper.size / 2 < platforms[i].x + platforms[i].xSiz)
{
let platformHalfYsiz = platforms[i].ySiz * 0.5;
let platformCenterY = platforms[i].y + platformHalfYsiz;
let distToPlatform = abs(jumperCollisionPoint - platformCenterY);
if (distToPlatform <= (platformHalfYsiz + jumper.deltaY)){
jumper.y = platforms[i].y - jumper.size / 2;
jumper.deltaY = 0;
hasJumperCollided = true;
break;
}
}
}
jumper.onPlatform = hasJumperCollided;
/*
changed the detection loop to detect if the onhect was going to move past the platform on the next frame, if so, put it on the platform
This solution was made by EthanStrawside on the p5js reddit after I had posted the fix question.
https://www.reddit.com/r/p5js/comments/1i3ns12/comment/m7p4d33/?context=3
this code was directly made for my code by another dev. It did not change a whole lot so I thought it was fair to use it.
*/
if (jumper.y > ground - jumper.size / 2) {
jumper.y = ground - jumper.size / 2;
jumper.deltaY = 0;
jumper.onPlatform = true;
}
jumper.x = constrain(jumper.x, 0, width);
jumper.y = constrain(jumper.y, 0, height);
fill(200, 220, 0)
ellipse(jumper.x, jumper.y, jumper.size, jumper.size);
for (let platform of platforms) {
platform.display();
}
}
function keyDownChecker(e) {
if (e.keyCode == 65) {
aPressed = true;
} else if (e.keyCode == 68) {
dPressed = true;
} else if (e.keyCode == 32) {
spacePressed = true;
}
}
function keyUpChecker(e) {
if (e.keyCode == 65) {
aPressed = false;
} else if (e.keyCode == 68) {
dPressed = false;
} else if (e.keyCode == 32) {
spacePressed = false;
}
}