xxxxxxxxxx
65
// Define variables for the game world
let world;
let boxSize = 30;
let ground;
let player;
function preload() {
// Load the planck library
game.loadScript('https://cdn.jsdelivr.net/npm/@flyover/planck.js', () => {
// Create a new physics world
world = planck.World({
gravity: planck.Vec2(0, 9.8)
});
// Define the ground body
ground = world.createBody();
ground.createFixture(planck.Edge(planck.Vec2(0, height), planck.Vec2(width, height)), {
friction: 0.5
});
// Define the player body
player = world.createDynamicBody({
position: planck.Vec2(width / 2, height - boxSize),
fixedRotation: true
});
player.createFixture(planck.Box(boxSize / 2, boxSize / 2), {
density: 1.0,
friction: 0.5
});
});
}
function setup() {
createCanvas(600, 400);
}
function draw() {
background(220);
// Step the physics simulation
if (world) {
world.step(1 / 60);
// Draw the ground
strokeWeight(2);
line(0, height, width, height);
// Draw the player
fill(255, 0, 0);
rectMode(CENTER);
rect(player.getPosition().x, player.getPosition().y, boxSize, boxSize);
}
// Handle player movement
if (keyIsDown(LEFT_ARROW)) {
player.applyForceToCenter(planck.Vec2(-200, 0), true);
}
if (keyIsDown(RIGHT_ARROW)) {
player.applyForceToCenter(planck.Vec2(200, 0), true);
}
if (keyIsDown(UP_ARROW) && Math.abs(player.getLinearVelocity().y) < 0.01) {
player.applyForceToCenter(planck.Vec2(0, -400), true);
}
}