1.首先写出小球的样式
f {width: 1200px;height: 800px;border: 1px solid red;position: relative;}.z {width: 100px;height: 100px;border-radius: 50%;background-color: red;position: absolute;left: 550px;top: 350px;}
2.然后给出空间范围,让小球进行镜面运动
let r = Mazth.floor(Math.random() * 1200)console.log(r)let x = 600, y = 4300let x_y = (x - r) / (y - 50)let dy = -1let dx = x_y * dylet ball = ElementById('ball')function startGame() {setInterval(() => {if (y <= 50 || y >= 750) {dy = -dy}if (x <= 50 || x >= 1150) {dx = -dx}x += dxy += dyball.style.left = x - 50 + 'px'p = y - 50 + 'px'ball.style.outline=title('')}, 0.1);}
3.最后的效果就是这样的
然后可以用键盘控制小球的运动,代码如下:
let dy=10;//按一次键盘,y轴移动的距离let dx=10;//按一次键盘,y轴移动的距离let x1=0,y1=0function start1(){let img1ElementById('img1')//2.感知键盘 keyCode:下40 右39 上38 左37document.οnkeydοwn=function(e){console.log(e.keyCode)switch(e.keyCode){case 40:console.log('下')y1+=p=y1+'px'break;case 39:console.log('右')x1+=dximg1.style.left=x1+'px'break;case 38:console.log('上')y1-=p=y1+'px'break;case 37:console.log('左')x1-=dximg1.style.left=x1+'px'break;}}}let x2=250,y2=0function start2(){let img2ElementById('img2')//2.感知键盘 keyCode:下40 右39 上38 左37document.οnkeydοwn=function(e){console.log(e.keyCode)switch(e.keyCode){case 40:console.log('下')y2+=p=y2+'px'break;case 39:console.log('右')x2+=dximg2.style.left=x2+'px'break;case 38:console.log('上')y2-=p=y2+'px'break;case 37:console.log('左')x2-=dximg2.style.left=x2+'px'break;}}}let x3=500,y3=0function start3(){let img3ElementById('img3')//2.感知键盘 keyCode:下40 右39 上38 左37document.οnkeydοwn=function(e){console.log(e.keyCode)switch(e.keyCode){case 40:console.log('下')y3+=p=y3+'px'break;case 39:console.log('右')x3+=dximg3.style.left=x3+'px'break;case 38:console.log('上')y3-=p=y3+'px'break;case 37:console.log('左')x3-=dximg3.style.left=x3+'px'break;}}}let x4=750,y4=0function start4(){let img4ElementById('img4')//2.感知键盘 keyCode:下40 右39 上38 左37document.οnkeydοwn=function(e){console.log(e.keyCode)switch(e.keyCode){case 40:console.log('下')y4+=p=y4+'px'break;case 39:console.log('右')x4+=dximg4.style.left=x4+'px'break;case 38:console.log('上')y4-=p=y4+'px'break;case 37:console.log('左')x4-=dximg4.style.left=x4+'px'break;}}}
本文发布于:2024-02-08 19:50:14,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170739314168489.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |