我希望這個div從A點到B點,反之亦然。問題是dist
變量(距離)永遠不會變爲0,它通常是1或-1(或其他一些其他值的範圍),這會導致div陷入僵局而無法到達任何地方。在我完整的代碼中,每當我打開頁面時,點A和B的位置都是隨機的。獲取距離爲0
下面的例子重現了這個問題。 要按預期設置工作#pointA { top: 5px; left: 5px; }
| #pointB { top: 5px; left: 105px; }
var score = 0, points = 0, boxMode = 0, speed, speedX, speedY, angleRadians,
distX, distY, dist;
var destinationX = $("#pointB").position().left;
var destinationY = $("#pointB").position().top;
var pointAPos = $("#pointA").position();
var pointAx = pointAPos.left;
var pointAy = pointAPos.top;
var pointBPos = $("#pointB").position();
var pointBx = pointBPos.left;
var pointBy = pointBPos.top;
var boxPos = $('#box').position();
var boxX = pointAx;
var boxY = pointAy;
\t
function calculateDistance(x, y) {
distX = boxX - x;
distY = boxY - y;
dist = Math.sqrt((distX*distX)+(distY*distY));
}
function boxMove() {
angleRadians = Math.atan2(-distX, -distY);
speed = 2;
speedX = speed * Math.sin(angleRadians);
speedY = speed * Math.cos(angleRadians);
\t
document.getElementById("box").style.left = boxX + "px";
document.getElementById("box").style.top = boxY + "px";
\t
boxX += speedX;
boxY += speedY;
}
function boxAI() {
calculateDistance(destinationX, destinationY);
if (!dist == 0) {
boxMove();
} else {
if (boxMode == 0) {
\t points += 1;
\t if (points == 50) {
\t // change destination to point A
\t \t destinationX = pointAx;
\t \t destinationY = pointAy;
\t \t boxMode = 1;
\t }
\t } else {
\t // change destination to point B
\t destinationX = pointBx;
\t destinationY = pointBy;
score += points;
points = 0;
\t boxMode = 0;
\t }
}
}
function mainLoop() {
boxAI();
$("#debug").html(points + " " + score + " " + boxMode);
requestAnimationFrame(mainLoop);
}
requestAnimationFrame(mainLoop);
#levelWrapper {
position: relative;
width: 400px;
height: 150px;
top: 2px;
margin: auto;
border: 1px solid red;
}
\t \t \t
#pointA {
position: absolute;
background: beige;
width: 45px;
height: 45px;
top: 3px;
left: 50px;
margin: auto;
}
\t \t \t
#pointB {
position: absolute;
background: beige;
width: 45px;
height: 45px;
top: 45px;
left: 195px;
margin: auto;
}
\t \t \t
#box {
position: absolute;
background: black;
height: 5px;
width: 5px;
}
#debug {
position: relative;
background: white;
width: 250px;
height: 120px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="debug"></div>
<div id="levelWrapper">
<div id="pointA">A</div>
<div id="pointB">B</div>
<div id="box"></div>
</div>
\t \t
<script src="jquery-3.2.1.js"></script>
<script type="text/javascript" src="woods_2.js"></script>
\t \t
</body>
注意:'sqrt()'永遠不能爲負數,所以你不需要''if'後面的。 – trincot
你可以創建一個stacksnippets來演示問題嗎? – guest271314
@ guest271314完成 – RealAnyOne