js实现投篮动作
实现投篮动作的基本思路
在JavaScript中实现投篮动作可以通过物理引擎模拟或手动计算抛物线轨迹。以下是两种常见方法:
使用Canvas绘制抛物线动画
通过Canvas绘制篮球的抛物线运动,需要计算篮球的位置随时间变化的轨迹:
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
let x = 50, y = canvas.height - 50;
let vx = 5, vy = -15; // 初始速度
const gravity = 0.2;
function drawBall() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(x, y, 20, 0, Math.PI * 2);
ctx.fillStyle = 'orange';
ctx.fill();
// 更新位置
x += vx;
y += vy;
vy += gravity;
// 边界检测
if (y > canvas.height - 20) {
y = canvas.height - 20;
vy *= -0.7; // 弹性系数
}
requestAnimationFrame(drawBall);
}
drawBall();
使用物理引擎(如Matter.js)
对于更复杂的物理效果,可以使用物理引擎库:
const Engine = Matter.Engine,
Render = Matter.Render,
World = Matter.World,
Bodies = Matter.Bodies;
const engine = Engine.create();
const render = Render.create({
element: document.body,
engine: engine,
options: { width: 800, height: 600 }
});
// 创建篮球和篮筐
const ball = Bodies.circle(100, 500, 20, {
restitution: 0.8,
render: { fillStyle: 'orange' }
});
const hoop = Bodies.rectangle(700, 300, 100, 10, {
isStatic: true,
angle: Math.PI * 0.1
});
World.add(engine.world, [ball, hoop]);
Engine.run(engine);
Render.run(render);
// 投篮动作
function shoot() {
Matter.Body.setVelocity(ball, { x: 15, y: -20 });
}
添加用户交互控制
可以通过鼠标或键盘事件触发投篮动作:
// 鼠标点击投篮
canvas.addEventListener('click', (e) => {
const power = calculatePower(e.clientX, e.clientY);
vx = power.x;
vy = power.y;
});
function calculatePower(clickX, clickY) {
const dx = clickX - x;
const dy = clickY - y;
const distance = Math.sqrt(dx * dx + dy * dy);
return {
x: dx / distance * 10,
y: dy / distance * 10
};
}
优化投篮物理模型
更精确的投篮模型应考虑出手角度和初速度:
$$ x(t) = v_0 \cdot \cos(\theta) \cdot t \ y(t) = v_0 \cdot \sin(\theta) \cdot t - \frac{1}{2}gt^2 $$
实现代码:
function projectileMotion(v0, angle) {
const radians = angle * Math.PI / 180;
const vx = v0 * Math.cos(radians);
const vy = v0 * Math.sin(radians);
return { vx, vy };
}
添加碰撞检测
检测篮球与篮筐的碰撞:

function checkCollision() {
const distance = Math.sqrt(
Math.pow(ball.x - hoop.x, 2) +
Math.pow(ball.y - hoop.y, 2)
);
return distance < (ball.radius + hoop.width/2);
}
这些方法可以根据实际需求组合使用,创建出更逼真的投篮模拟效果。






