Get the App
SLTechnology News&Howtos  ›  Development  › 

How to make a bouncing ball game with js

Shulou Source: shulou.com Published: 2022-06-03 14:56:21 09月11日 Update

This article introduces the relevant knowledge of "how to use js to make bouncing ball games". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

On a whim, I wrote a case of a small ball bouncing back and forth for your reference. The details are as follows.

Mainly uses the margin-left / top value for displacement, of course, you can also use positioning to do.

The cases used in this case are:

DOM element acquisition

DOM style operation

.offsetWidth gets the element width

.offsetHeight gets the element height

SetInterval () timer

Upper code

Overall use of native js

/ / style style * {margin: 0; padding: 0;} # box {width: 500px; height: 600px; background-color: # eee; box-shadow: 00 10px 0 # 000; margin: auto; overflow: hidden; position: relative Margin-top: 50px;} # box div {width: 50px; height: 50px; border-radius: 50%; background-color: # fff; position: absolute } var box = document.getElementById ("box"); var cir = document.getElementById ("cir") var cirs = box.querySelectorAll ("div"); collMove (box, cir, 6); collMove (box, cirs [1], 7); collMove (box, cirs [2], 8); collMove (box, cirs [3], 9) CollMove (box, cirs [4], 10); collMove (box, cirs [5], 10); collMove (box, cirs [6], 11); / * change the color of the element when it pops up at the boundary * @ param {container acquisition} box * @ param {bounce element acquisition} cir * @ param {bounce speed} speed * / function collMove (box, cir, speed) {/ / method package var oDiv = box / / get container var oCir = cir; / / get the elements in the container var xMax = oDiv.offsetWidth-oCir.offsetWidth; / / container maximum X axis boundary var yMax = oDiv.offsetHeight-oCir.offsetHeight; / / container maximum Y axis boundary var motionX = 0; / / element X axis coordinate initialization var motionY = 0; / / element y axis coordinate initialization () = > {var speedX = speed / / x-axis offset var speedY = speed; / / y-axis offset setInterval (() = > {motionX + = speedX; / / X-axis offset motionY + = speedY; / / y-axis offset if (motionX > = xMax) {/ / detect whether the X-axis right boundary motionX = xMax / / set the X axis coordinate to the maximum right boundary of the x axis speedX =-speedX; / / the x axis offset reverses randColor (oCir); / / change the color} else if (motionX = yMax) {motionY = yMax; speedY =-speedY randColor (oCir);} else if (motionY)

Tags: Elements containers coordinates methods boundaries offsets balls maximum content color encapsulation production right that is more styles cases knowledge loops detection Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information Docker Apple MariaDB MySQL