簡體   English   中英

"如果連續朝一個方向前進,您如何反轉球的方向?"

[英]How do you reverse the direction of a ball if continuously going in one direction?

 var velocity = 100; var positionX = 0; var ball = document.getElementById('ball'); function moveBall() { var Xmin = 0; var Xmax = 300; positionX = positionX + velocity; ball.style.left = positionX + 'px'; } setInterval(moveBall, 100);<\/code><\/pre>
 img { position: absolute; }<\/code><\/pre>
 <img id="ball" width="150" height="150" src="https:\/\/tr.seaicons.com\/wp-content\/uploads\/2016\/11\/Volleyball-Ball-icon.png"\/><\/code><\/pre>

我已經聲明了我的全局變量,然后是一個移動球的函數,然后是一個setInterval<\/code> 。 但是,我似乎無法找到正確的方法來反轉不斷移動到屏幕右側直到不再可見的球。 它是一種反向方法或設置條件的問題嗎?

"

在下面的解決方案中, velocity變量用於改變移動速度。 updateDirection()方法用於通過檢查positionX值來更改新的方向信息。

 var ball = document.getElementById('ball'); /* This variable is used to change the movement speed. */ const velocity = 50; /* This variable is used to change the amount of movement per unit time. */ const step = 10; /* This variable stores the current or target position of the <img> element. */ var positionX = 0; /* This variable stores the minimum position value. */ const xMin = 0; /* This variable stores the maximum position value. */ const xMax = 300; /* true: right move, false: left move */ var direction = true; /* This method is used to change the direction of movement. */ function updateDirection() { if(positionX == xMax) direction = false; else if(positionX == xMin) direction = true; } function moveBall() { updateDirection(); if(direction) positionX += step; else positionX -= step; ball.style.left = `${positionX}px`; console.clear(); console.log(`Direction: ${direction ? "right" : "left"} Position: ${positionX} `); } /* Update the velocity value to change the movement speed. */ setInterval(moveBall, velocity);
 img { position: absolute; }
 <img id="ball" width="150" height="150" src="https://tr.seaicons.com/wp-content/uploads/2016/11/Volleyball-Ball-icon.png"/>

讓我給你一些見解:

要設置碰撞,您可以獲得球的 y + 或 - 半徑,看看它是大於邊界的還是小於零...

像這樣:

if (y + radius > innerHeight)<\/code>和else if (y - radius < 0)<\/code>

那么你可以類似地比較 x :

if (x + radius > innerWidth)<\/code>和else if (x - radius < 0)<\/code>

通過velocity *= -1<\/code>或velocity = 0-velocity<\/code> ,您可以反轉球的方向。<\/strong>

您可以查看本教程了解更多信息: https<\/a> :\/\/www.geeksforgeeks.org\/how-to-build-a-bounce-ball-with-html-and-javascript\/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM