Asthetic car
unknown
plain_text
2 months ago
6.1 kB
3
Indexable
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Open-World Racing Game</title> <style> body { margin: 0; padding: 0; overflow: hidden; } canvas { display: block; background: #87CEEB; /* sky blue color */ } </style> </head> <body> <canvas id="gameCanvas"></canvas> <script> const canvas = document.getElementById('gameCanvas'); const ctx = canvas.getContext('2d'); let carX = canvas.width / 2; let carY = canvas.height / 2; let carSpeed = 2; // Resize canvas to full window canvas.width = window.innerWidth; canvas.height = window.innerHeight; // Basic car object const car = { width: 50, height: 30, color: 'red', draw: function() { ctx.fillStyle = this.color; ctx.fillRect(carX, carY, this.width, this.height); } }; // Key controls const keys = { up: false, down: false, left: false, right: false }; // Event listeners for keydown and keyup window.addEventListener('keydown', (e) => { if (e.key === 'ArrowUp') keys.up = true; if (e.key === 'ArrowDown') keys.down = true; if (e.key === 'ArrowLeft') keys.left = true; if (e.key === 'ArrowRight') keys.right = true; }); window.addEventListener('keyup', (e) => { if (e.key === 'ArrowUp') keys.up = false; if (e.key === 'ArrowDown') keys.down = false; if (e.key === 'ArrowLeft') keys.left = false; if (e.key === 'ArrowRight') keys.right = false; }); // Main game loop function gameLoop() { ctx.clearRect(0, 0, canvas.width, canvas.height); // clear screen // Control the car's movement if (keys.up) carY -= carSpeed; if (keys.down) carY += carSpeed; if (keys.left) carX -= carSpeed; if (keys.right) carX += carSpeed; // Draw the car car.draw(); // Keep the car within canvas bounds if (carX < 0) carX = 0; if (carY < 0) carY = 0; if (carX + car.width > canvas.width) carX = canvas.width - car.width; if (carY + car.height > canvas.height) carY = canvas.height - car.height; requestAnimationFrame(gameLoop); // Repeat the game loop } // Start the game loop gameLoop(); </script> </body> </html> } }) }) } } } } }
Editor is loading...
Leave a Comment