2d html hill climb racing game using matter js. one page full html
- User
2d html hill climb racing game using matter js. one page full html
- Assistant
2d html hill climb racing game using matter js. one page full html
Sure! Below is a simple 2D hill climb racing game implemented using Matter.js, all contained within a single HTML file. This basic example features a car with two wheels, a hilly terrain, and keyboard controls to move the car left and right.
Copy and paste the following code into a new HTML file and open it in your browser to play the game:
<!DOCTYPE html>
<html>
<head>
<title>2D Hill Climb Racing Game</title>
<!-- Include Matter.js library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.19.0/matter.min.js"></script>
<style>
body { margin: 0; overflow: hidden; }
canvas { display: block; }
</style>
</head>
<body>
<canvas id="world"></canvas>
<script>
// Module aliases
const { Engine, Render, Runner, World, Bodies, Body, Events, Constraint } = Matter;
// Create engine
const engine = Engine.create();
const world = engine.world;
// Create renderer
const render = Render.create({
canvas: document.getElementById('world'),
engine: engine,
options: {
width: window.innerWidth,
height: window.innerHeight,
wireframes: false,
background: '#87CEEB',
hasBounds: true,
},
});
Render.run(render);
// Create runner
const runner = Runner.create();
Runner.run(runner, engine);
// Adjust the canvas size when the window is resized
window.addEventListener('resize', () => {
render.canvas.width = window.innerWidth;
render.canvas.height = window.innerHeight;
});
// Create terrain using a chain of vertices
const terrainVertices = [
{ x: 0, y: window.innerHeight * 0.75 },
{ x: window.innerWidth * 0.25, y: window.innerHeight * 0.65 },
{ x: window.innerWidth * 0.5, y: window.innerHeight * 0.8 },
{ x: window.innerWidth * 0.75, y: window.innerHeight * 0.7 },
{ x: window.innerWidth * 1.0, y: window.innerHeight * 0.75 },
{ x: window.innerWidth * 1.25, y: window.innerHeight * 0.6 },
{ x: window.innerWidth * 1.5, y: window.innerHeight * 0.8 },
{ x: window.innerWidth * 1.75, y: window.innerHeight * 0.7 },
{ x: window.innerWidth * 2.0, y: window.innerHeight * 0.75 },
{ x: window.innerWidth * 2.0, y: window.innerHeight },
{ x: 0, y: window.innerHeight },
];
const terrain = Bodies.fromVertices(
window.innerWidth,
window.innerHeight / 2,
[terrainVertices],
{
isStatic: true,
render: {
fillStyle: '#228B22',
},
},
true,
);
World.add(world, terrain);
// Create vehicle components
const wheelRadius = 20;
const wheelA = Bodies.circle(150, window.innerHeight * 0.7 - wheelRadius, wheelRadius, {
friction: 0.8,
restitution: 0.2,
render: { fillStyle: '#666' },
});
const wheelB = Bodies.circle(250, window.innerHeight * 0.7 - wheelRadius, wheelRadius, {
friction: 0.8,
restitution: 0.2,
render: { fillStyle: '#666' },
});
const vehicleBody = Bodies.rectangle(200, window.innerHeight * 0.7 - 60, 120, 30, {
density: 0.001,
frictionAir: 0.001,
friction: 0.8,
render: { fillStyle: '#FF0000' },
});
// Connect wheels to the body with constraints
const axelA = Constraint.create({
bodyA: wheelA,
bodyB: vehicleBody,
pointB: { x: -50, y: 0 },
stiffness: 1,
length: 0,
});
const axelB = Constraint.create({
bodyA: wheelB,
bodyB: vehicleBody,
pointB: { x: 50, y: 0 },
stiffness: 1,
length: 0,
});
World.add(world, [wheelA, wheelB, vehicleBody, axelA, axelB]);
// Keyboard control setup
const keys = {};
document.body.addEventListener('keydown', (e) => {
keys[e.keyCode] = true;
});
document.body.addEventListener('keyup', (e) => {
keys[e.keyCode] = false;
});
// Apply controls to the vehicle
Events.on(engine, 'beforeUpdate', () => {
const forceMagnitude = 0.0005 * vehicleBody.mass;
if (keys[39]) {
// Right arrow key
Body.applyForce(wheelA, wheelA.position, { x: forceMagnitude, y: 0 });
Body.applyForce(wheelB, wheelB.position, { x: forceMagnitude, y: 0 });
}
if (keys[37]) {
// Left arrow key
Body.applyForce(wheelA, wheelA.position, { x: -forceMagnitude, y: 0 });
Body.applyForce(wheelB, wheelB.position, { x: -forceMagnitude, y: 0 });
}
});
// Center the viewport on the vehicle
Events.on(engine, 'afterUpdate', () => {
const boundsWidth = render.bounds.max.x - render.bounds.min.x;
const boundsHeight = render.bounds.max.y - render.bounds.min.y;
const viewportCentre = {
x: render.bounds.min.x + boundsWidth * 0.5,
y: render.bounds.min.y + boundsHeight * 0.5,
};
// Smoothly move the viewport towards the vehicle
const deltaCentre = {
x: vehicleBody.position.x - viewportCentre.x,
y: vehicleBody.position.y - viewportCentre.y,
};
render.bounds.min.x += deltaCentre.x * 0.05;
render.bounds.max.x += deltaCentre.x * 0.05;
render.bounds.min.y += deltaCentre.y * 0.05;
render.bounds.max.y += deltaCentre.y * 0.05;
});
// Prevent objects from falling out of the world
const ground = Bodies.rectangle(
window.innerWidth,
window.innerHeight + 50,
window.innerWidth * 10,
100,
{ isStatic: true },
);
World.add(world, ground);
</script>
</body>
</html>
Instructions:
Explanation:
Matter.js Setup: The code initializes the Matter.js engine, renderer, and runner to simulate physics and render the scene.
Terrain: A hilly terrain is created using an array of vertices to define the shape. The Bodies.fromVertices method creates a complex static body that represents the hills.
Vehicle: The vehicle consists of a rectangular body and two circular wheels connected by constraints (Constraint.create). The wheels are dynamic bodies that can rotate and move independently.
Controls: Keyboard event listeners track when the left or right arrow keys are pressed or released. Forces are applied to the wheels based on the keys pressed, propelling the car forward or backward.
Camera Movement: The viewport is adjusted to center on the vehicle's position after each update, providing a smooth camera following effect.
Prevent Falling: An invisible ground is added below the terrain to catch the car if it falls off the hills.
Note:
Enjoy your game! Let me know if you need further assistance or enhancements.
Not yet included in a published release.