我现在需要写一个基于JavaScript的小球物理碰撞效果,你能帮我写代码吗
时间: 2023-04-02 21:04:14 浏览: 63
当然可以,以下是一个基于JavaScript的小球物理碰撞效果的代码示例:
```javascript
// 定义画布和小球的属性
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var balls = [];
var colors = ["#FF000", "#00FF00", "#000FF", "#FFFF00", "#00FFFF", "#FF00FF"];
// 定义小球的构造函数
function Ball(x, y, dx, dy, radius, color) {
this.x = x;
this.y = y;
this.dx = dx;
this.dy = dy;
this.radius = radius;
this.color = color;
}
// 定义小球的绘制函数
Ball.prototype.draw = function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, , Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
ctx.closePath();
}
// 定义小球的更新函数
Ball.prototype.update = function() {
if (this.x + this.radius > canvas.width || this.x - this.radius < ) {
this.dx = -this.dx;
}
if (this.y + this.radius > canvas.height || this.y - this.radius < ) {
this.dy = -this.dy;
}
this.x += this.dx;
this.y += this.dy;
}
// 定义小球的碰撞检测函数
function collisionDetection(ball1, ball2) {
var dx = ball1.x - ball2.x;
var dy = ball1.y - ball2.y;
var distance = Math.sqrt(dx * dx + dy * dy);
if (distance < ball1.radius + ball2.radius) {
ball1.dx = -ball1.dx;
ball1.dy = -ball1.dy;
ball2.dx = -ball2.dx;
ball2.dy = -ball2.dy;
}
}
// 定义动画函数
function animate() {
requestAnimationFrame(animate);
ctx.clearRect(, , canvas.width, canvas.height);
for (var i = ; i < balls.length; i++) {
balls[i].draw();
balls[i].update();
for (var j = i + 1; j < balls.length; j++) {
collisionDetection(balls[i], balls[j]);
}
}
}
// 创建小球并添加到数组中
for (var i = ; i < 50; i++) {
var radius = Math.random() * 20 + 10;
var x = Math.random() * (canvas.width - radius * 2) + radius;
var y = Math.random() * (canvas.height - radius * 2) + radius;
var dx = (Math.random() - .5) * 10;
var dy = (Math.random() - .5) * 10;
var color = colors[Math.floor(Math.random() * colors.length)];
balls.push(new Ball(x, y, dx, dy, radius, color));
}
// 开始动画
animate();
```