我希望这个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