JSFiddle - React, Tailwind, and code Playground
by Yorrick Bakker
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.5.5/p5.js"></script>
JavaScript
function Player(location, width, height, speed, weight) {
this.pos = location;
this.width = width;
this.height = height;
this.velocity = speed;
this.mass = weight;
this.grav = new p5.Vector(0, this.mass * 10);
}
function Wall(location, width, height) {
this.pos = location;
this.width = width;
this.height = height;
}
var p1 = new Player(new p5.Vector(-100, 0), 50, 70, new p5.Vector(0, 0), 1);
var wall1 = new Wall(new p5.Vector(100, -100), 50, 50);
var collision = false;
var jump = new p5.Vector(0, -100);
function setup() {
createCanvas(500, 500);
background(100);
}
function draw() {
// Set zero-point
translate(-p1.pos.x * 0.95 + 100, height - p1.height);
// Apply gravity if p1 is not touching object
if (p1.pos.y > 0) {
// Do not apply p1.grav
collision = true;
} else {
p1.pos.add(p1.grav);
collision = false;
}
noStroke();
fill(55, 37, 73);
background(100);
rect(p1.pos.x, p1.pos.y, p1.width, p1.height);
rect(wall1.pos.x, wall1.pos.y, wall1.width, wall1.height);
if (p1.pos.x < -p1.width * 2) {
p1.velocity.x = 10;
p1.pos.add(p1.velocity.x);
} else {
if (keyIsDown(LEFT_ARROW)) {
p1.velocity.x = 5;
p1.pos.sub(p1.velocity.x);
} else if (keyIsDown(RIGHT_ARROW)) {
p1.velocity.x = 5;
p1.pos.add(p1.velocity.x);
}
}
}
function keyPressed() {
if (key == ' ') {
p1.pos.y += jump.y;
}
}