课堂作业-碰撞测试

发布时间 2023-06-08 11:34:49作者: miriz

使两个圆当用鼠标拖动其中一个圆形接触到另一个圆形时,另一个圆形变黑.

1,制作两个圆形:


<html lang="en">
<head>
<meta charset="UTF-8">
<title>碰撞测试</title>
<style>
body{
margin: 0
}
#box{
width: 100px;
height: 100px;
background: lightgreen;
position: absolute;
top: 0;
left: 0;
border-radius: 50%;
}

#box1 {
width: 100px;
height: 100px;
background: lightcoral;
position: absolute;
top: 200px;
left: 300px;
z-index: -1;
border-radius: 50%;
}

</style>
</head>
<body>
<div id="box"></div>
<div id="box1"></div>
</body>
</html>
 

效果如下:

2,设置script使鼠标移动圆形效果和接触变黑效果实现

 1 <script>
 2     let box = document.getElementById('box')
 3     let box1 = document.getElementById('box1')
 4     box.onmousedown = function (event) {
 5         let chaX = event.clientX - box.offsetLeft
 6         let chaY = event.clientY - box.offsetTop
 7 
 8 
 9         document.onmousemove = function (event) {
10             box.style.left = event.clientX - chaX + 'px'
11             box.style.top = event.clientY - chaY + 'px'
12             if ((box.offsetLeft - box1.offsetLeft) * (box.offsetLeft - box1.offsetLeft) +
13                 (box.offsetTop - box1.offsetTop) * (box.offsetTop - box1.offsetTop) >
14                 (box.offsetWidth / 2 + box1.offsetWidth / 2) * (box.offsetWidth / 2 + box1.offsetWidth / 2)) {
15                 box1.style.background = 'lightcoral'
16             } else {
17                 box1.style.background = 'black'
18             }
19 
20         }
21 
22         document.onmouseup = function () {
23             document.onmousemove = null
24         }
25     }
26 
27 
28     box1.onmousedown = function (event) {
29         let chaX = event.clientX - box1.offsetLeft
30         let chaY = event.clientY - box1.offsetTop
31         document.onmousemove = function (event) {
32             box1.style.left = event.clientX - chaX + 'px'
33             box1.style.top = event.clientY - chaY + 'px'
34             if ((box1.offsetLeft - box.offsetLeft) * (box1.offsetLeft - box.offsetLeft) +
35                 (box1.offsetTop - box.offsetTop) * (box1.offsetTop - box.offsetTop) >
36                 (box1.offsetWidth / 2 + box.offsetWidth / 2) * (box1.offsetWidth / 2 + box.offsetWidth / 2)) {
37                 box.style.background = 'lightgreen'
38             } else {
39                 box.style.background = 'black'
40             }
41 
42 
43 
44         }
45         document.onmouseup = function () {
46             document.onmousemove = null
47         }}
48 </script>

效果如下:

此时两个圆形皆可用鼠标拖动.

当拖动粉色圆形与绿色圆形接触时:

当拖动绿色圆形与粉色圆形接触时:

 

本次代码缺陷:未能实现当其中一个圆形覆盖另一个圆形时,控制器提供反馈.