Hi there!
I’ve hit a snag in my code. I want to be able to make a game where the player (a rect) jumps over obstacles. Similar to the no wifi Dino game. I’ve added code to make the player character flip when they jump.
show() {
angleMode(DEGREES);
rectMode(CENTER);
noStroke();
fill(150);
// Rotate player when jumping
if (this.y < height - 25) {
translate(this.x, this.y);
rotate(this.angle);
this.angle = this.angle + 7;
rect(0, 0, this.s, this.s);
} else {
rect(this.x, this.y, this.s, this.s);
}
}
However, as the player jumps, the obstacles rotate along with the player while moving. I want the obstacles to simply move across the screen. My question is, how can I make the obstacles move toward the player without rotating when the player jumps?
Full code here:
let player;
let obstacle = [];
function setup() {
createCanvas(900, 500);
player = new Player();
}
// Press Space to Jump
function keyPressed() {
if (key == ' ') {
player.jumpSp();
}
}
function draw() {
if (random(1) < 0.01){
obstacle.push(new Obstacle());
}
background(220);
player.show();
player.jump();
for(let obs of obstacle){
obs.move();
obs.show();
}
}
// Player properties
class Player {
constructor() {
this.s = 50;
this.x = 50;
this.y = height - 25;
this.j = 0;
this.gravity = 1;
this.angle = 0;
}
// Jump Speed
jumpSp() {
this.j = -15;
}
// Jump movement
// Gives player gravity
// Keeps player from leaving canvas
jump() {
this.y += this.j;
this.j += this.gravity
this.y = constrain(this.y, 25, height - 25)
}
show() {
angleMode(DEGREES);
rectMode(CENTER);
noStroke();
fill(150);
// Rotate player when jumping
if (this.y < height - 25) {
translate(this.x, this.y);
rotate(this.angle);
this.angle = this.angle + 7;
rect(0, 0, this.s, this.s);
} else {
rect(this.x, this.y, this.s, this.s);
}
}
}
// Obstacle properties
class Obstacle {
constructor(){
this.w = 50;
this.h = 70;
this.x = width;
this.y = height - this.h;
}
move(){
this.x -= 5;
}
show(){
angleMode(RADIUS);
rectMode(CORNER);
noStroke();
fill(0);
rect(this.x,this.y,this.w,this.h);
}
}