Make a 2D basketball game using HTML canvas without relying on external assets, I should…
- User
Make a 2D basketball game using HTML canvas without relying on external assets, I should be able to pick the ball when the mouse is down on the ball, move it around, then throw it to score, make sure to limit the mouse movements so I don't drop it and score free points, it should automatically throw the ball if it reaches the limit
- Assistant
Sure! Below is a simple 2D basketball game implemented using HTML Canvas and JavaScript. In this game, you can click and hold the mouse on the basketball to pick it up, drag it around within a certain limit, and release to throw the ball towards the basket. If you reach the movement limit while dragging the ball, it will automatically throw the ball.
Here's the complete code:
<!DOCTYPE html> <html> <head> <title>2D Basketball Game</title> <style> body { margin: 0; overflow: hidden; background: #87CEEB; /* Sky blue background */ } </style> </head> <body> <canvas id="gameCanvas"></canvas> <script> // Get the canvas element and set its size const canvas = document.getElementById('gameCanvas'); const ctx = canvas.getContext('2d'); canvas.width = window.innerWidth; canvas.height = window.innerHeight; // Define the ball object const ball = { x: canvas.width / 2, y: canvas.height - 50, radius: 20, color: 'orange', isDragging: false, startX: 0, startY: 0, movementLimit: 150, // Limit for mouse movement while dragging totalDistance: 0, velocity: { x: 0, y: 0 }, gravity: 0.5, }; // Define the basket const basket = { x: canvas.width / 2 - 50, y: 100, width: 100, height: 10, }; let score = 0; let isBallThrown = false; // Event listeners for mouse interaction canvas.addEventListener('mousedown', onMouseDown); canvas.addEventListener('mouseup', onMouseUp); canvas.addEventListener('mousemove', onMouseMove); function onMouseDown(e) { const rect = canvas.getBoundingClientRect(); const mouseX = e.clientX - rect.left; const mouseY = e.clientY - rect.top; // Check if the mouse is on the ball if (isInsideBall(mouseX, mouseY)) { ball.isDragging = true; ball.startX = mouseX; ball.startY = mouseY; ball.totalDistance = 0; ball.velocity = { x: 0, y: 0 }; isBallThrown = false; } } function onMouseUp(e) { if (ball.isDragging) { ball.isDragging = false; throwBall(); } } function onMouseMove(e) { if (ball.isDragging) { const rect = canvas.getBoundingClientRect(); const mouseX = e.clientX - rect.left; const mouseY = e.clientY - rect.top; // Calculate the movement distance const dx = mouseX - ball.x; const dy = mouseY - ball.y; const distance = Math.sqrt(dx * dx + dy * dy); ball.totalDistance += distance; // Check if movement limit is reached if (ball.totalDistance >= ball.movementLimit) { ball.isDragging = false; throwBall(); return; } // Update ball position ball.x = mouseX; ball.y = mouseY; } } function isInsideBall(x, y) { const dx = x - ball.x; const dy = y - ball.y; return dx * dx + dy * dy <= ball.radius * ball.radius; } function throwBall() { // Set the velocity based on the drag distance const dx = ball.startX - ball.x; const dy = ball.startY - ball.y; ball.velocity.x = -dx * 0.1; ball.velocity.y = -dy * 0.1; isBallThrown = true; } function update() { if (isBallThrown) { // Update ball position with velocity and gravity ball.x += ball.velocity.x; ball.y += ball.velocity.y; ball.velocity.y += ball.gravity; // Check for scoring if (checkScore()) { score += 1; resetBall(); } // Check if ball is out of bounds if (ball.y - ball.radius > canvas.height || ball.x + ball.radius < 0 || ball.x - ball.radius > canvas.width) { resetBall(); } } draw(); requestAnimationFrame(update); } function checkScore() { // Simple collision detection with the basket if ( ball.x > basket.x && ball.x < basket.x + basket.width && ball.y - ball.radius < basket.y + basket.height && ball.y + ball.radius > basket.y ) { return true; } return false; } function resetBall() { ball.x = canvas.width / 2; ball.y = canvas.height - 50; ball.velocity = { x: 0, y: 0 }; isBallThrown = false; } function draw() { // Clear the canvas ctx.clearRect(0, 0, canvas.width, canvas.height); // Draw the basket ctx.fillStyle = 'brown'; ctx.fillRect(basket.x, basket.y, basket.width, basket.height); // Draw the backboard ctx.fillStyle = 'black'; ctx.fillRect(basket.x + basket.width / 2 - 5, basket.y - 50, 10, 50); // Draw the ball ctx.beginPath(); ctx.arc(ball.x, ball.y, ball.radius, 0, Math.PI * 2); ctx.fillStyle = ball.color; ctx.fill(); ctx.closePath(); // Draw the score ctx.fillStyle = 'black'; ctx.font = '24px Arial'; ctx.fillText('Score: ' + score, 20, 30); } // Start the game loop update(); // Adjust canvas size when window is resized window.addEventListener('resize', function () { canvas.width = window.innerWidth; canvas.height = window.innerHeight; resetBall(); }); </script> </body> </html>Explanation:
-
Canvas Setup:
- The canvas is set to fill the entire browser window.
- The canvas size is adjusted when the window is resized.
-
Ball Object:
- Represents the basketball with properties like position (
x,y),radius,color, and velocity. isDraggingindicates whether the ball is being dragged.movementLimitsets the limit for mouse movement while dragging.
- Represents the basketball with properties like position (
-
Basket Object:
- Represents the basket located at a fixed position near the top of the canvas.
-
Mouse Events:
mousedown: Checks if the click is on the ball and starts dragging.mousemove: Updates the ball's position while dragging and checks if the movement limit is reached.mouseup: Stops dragging and throws the ball.
-
Throwing Mechanism:
- When the ball is thrown, its velocity is set based on the drag distance.
- Gravity is applied to simulate a realistic arc movement.
-
Movement Limit:
- If the total distance moved while dragging exceeds
movementLimit, the ball is automatically thrown to prevent cheating.
- If the total distance moved while dragging exceeds
-
Scoring:
- Checks if the ball intersects with the basket area.
- If a score occurs, the
scorevariable is incremented.
-
Game Loop (
updatefunction):- Updates the ball's position if it has been thrown.
- Redraws the entire scene each frame.
-
Drawing:
- The basket is drawn as a rectangle.
- The ball is drawn as a circle.
- The score is displayed at the top-left corner.
How to Use:
-
Save the Code:
- Copy the entire code and paste it into a text editor.
- Save the file with an
.htmlextension (e.g.,basketball_game.html).
-
Open in Browser:
- Open the saved HTML file in a modern web browser (like Chrome, Firefox, or Edge).
-
Play the Game:
- Pick Up the Ball:
- Click and hold the mouse button down on the ball to pick it up.
- Drag the Ball:
- While holding the mouse button, move the mouse to drag the ball.
- You can only move the ball within a certain limit to prevent cheating.
- Throw the Ball:
- Release the mouse button to throw the ball towards the basket.
- If you reach the movement limit, the ball will automatically be thrown.
- Score Points:
- Aim to get the ball into the basket to score points.
- The score is displayed at the top-left corner.
- Pick Up the Ball:
-
Reset and Replay:
- After the ball is thrown, it will reset if it scores or goes out of bounds.
- You can then pick up and throw the ball again.
Notes:
- Adjusting Difficulty:
- You can modify
ball.movementLimitto change how far you can drag the ball before it automatically throws. - Changing the gravity (
ball.gravity) or the velocity multipliers (0.1inthrowBall) will affect the ball's movement.
- You can modify
- Enhancements:
- Add sounds for throwing and scoring.
- Improve graphics by adding images or more detailed drawings.
- Implement levels or moving baskets for added challenge.
- Responsiveness:
- The canvas adjusts to window resizing to ensure the game remains full-screen.
Understanding the Mechanics:
-
The game uses basic physics principles to simulate the throw:
- The initial velocity is determined by the inverse of the drag distance (
dx,dy). - Gravity affects the vertical velocity over time, creating a parabolic trajectory.
- The initial velocity is determined by the inverse of the drag distance (
-
The collision detection for scoring is simplified:
- It checks if the ball's position overlaps with the basket's position.
Feel free to modify and enhance the game to suit your preferences! Enjoy playing and challenging yourself to score as many points as possible.
-