01-object-hit-test.html 完成的碰撞检测
时间: 2023-06-16 08:02:52 浏览: 59
碰撞检测是指在游戏或者模拟中检测两个物体是否发生了碰撞。在网页开发中,我们可以使用JavaScript实现简单的碰撞检测。在01-object-hit-test.html中,实现了一个基于Canvas的简单碰撞检测示例,通过判断两个圆形物体之间的距离是否小于它们的半径之和来判断它们是否发生了碰撞。
具体实现步骤如下:
1. 定义两个圆形物体(对象),包括其位置、半径、颜色等属性。
```
var circle1 = {
x: 100,
y: 100,
r: 50,
color: "#FF0000"
};
var circle2 = {
x: 200,
y: 200,
r: 80,
color: "#0000FF"
};
```
2. 在Canvas中绘制两个圆形物体。
```
ctx.beginPath();
ctx.arc(circle1.x, circle1.y, circle1.r, 0, 2 * Math.PI);
ctx.fillStyle = circle1.color;
ctx.fill();
ctx.beginPath();
ctx.arc(circle2.x, circle2.y, circle2.r, 0, 2 * Math.PI);
ctx.fillStyle = circle2.color;
ctx.fill();
```
3. 计算两个圆形物体之间的距离。
```
var distance = Math.sqrt(Math.pow(circle1.x - circle2.x, 2) + Math.pow(circle1.y - circle2.y, 2));
```
4. 判断两个圆形物体是否发生碰撞。
```
if (distance < circle1.r + circle2.r) {
console.log("Collision detected!");
}
```
完整代码如下:
```
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Object Hit Test</title>
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var circle1 = {
x: 100,
y: 100,
r: 50,
color: "#FF0000"
};
var circle2 = {
x: 200,
y: 200,
r: 80,
color: "#0000FF"
};
ctx.beginPath();
ctx.arc(circle1.x, circle1.y, circle1.r, 0, 2 * Math.PI);
ctx.fillStyle = circle1.color;
ctx.fill();
ctx.beginPath();
ctx.arc(circle2.x, circle2.y, circle2.r, 0, 2 * Math.PI);
ctx.fillStyle = circle2.color;
ctx.fill();
var distance = Math.sqrt(Math.pow(circle1.x - circle2.x, 2) + Math.pow(circle1.y - circle2.y, 2));
if (distance < circle1.r + circle2.r) {
console.log("Collision detected!");
}
</script>
</body>
</html>
```