本文主要是介绍用js制作接球小游戏,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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 = document.getElementById('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'ball.style.top = 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 img1=document.getElementById('img1')//2.感知键盘 keyCode:下40 右39 上38 左37document.οnkeydοwn=function(e){console.log(e.keyCode)switch(e.keyCode){case 40:console.log('下')y1+=dyimg1.style.top=y1+'px'break;case 39:console.log('右')x1+=dximg1.style.left=x1+'px'break;case 38:console.log('上')y1-=dyimg1.style.top=y1+'px'break;case 37:console.log('左')x1-=dximg1.style.left=x1+'px'break;}}}let x2=250,y2=0function start2(){let img2=document.getElementById('img2')//2.感知键盘 keyCode:下40 右39 上38 左37document.οnkeydοwn=function(e){console.log(e.keyCode)switch(e.keyCode){case 40:console.log('下')y2+=dyimg2.style.top=y2+'px'break;case 39:console.log('右')x2+=dximg2.style.left=x2+'px'break;case 38:console.log('上')y2-=dyimg2.style.top=y2+'px'break;case 37:console.log('左')x2-=dximg2.style.left=x2+'px'break;}}}let x3=500,y3=0function start3(){let img3=document.getElementById('img3')//2.感知键盘 keyCode:下40 右39 上38 左37document.οnkeydοwn=function(e){console.log(e.keyCode)switch(e.keyCode){case 40:console.log('下')y3+=dyimg3.style.top=y3+'px'break;case 39:console.log('右')x3+=dximg3.style.left=x3+'px'break;case 38:console.log('上')y3-=dyimg3.style.top=y3+'px'break;case 37:console.log('左')x3-=dximg3.style.left=x3+'px'break;}}}let x4=750,y4=0function start4(){let img4=document.getElementById('img4')//2.感知键盘 keyCode:下40 右39 上38 左37document.οnkeydοwn=function(e){console.log(e.keyCode)switch(e.keyCode){case 40:console.log('下')y4+=dyimg4.style.top=y4+'px'break;case 39:console.log('右')x4+=dximg4.style.left=x4+'px'break;case 38:console.log('上')y4-=dyimg4.style.top=y4+'px'break;case 37:console.log('左')x4-=dximg4.style.left=x4+'px'break;}}}
这篇关于用js制作接球小游戏的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!