我一直在玩 JavaScript/JQuery,并决定创建一个小程序,让球在矩形边界区域周围弹跳。我相信我的代码逻辑应该是有意义的,但由于某种原因,我无法让它改变方向。更奇怪的是,我将球的 x 和 y 位置作为文本放在上面,但它似乎是静态卡住的(它不会改变),但是当我检查它留下的元素时,我看到顶部的 css 参数正在改变时间。
这是代码:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">
</script>
<style>
.ball {
width: 50px;
height: 50px;
background: red;
-moz-border-radius: 50px;
-webkit-border-radius: 50px;
border-radius: 50px;
position: absolute;
}
.boundary {
width: 700px;
height: 500px;
background: #AAAAAA;
border-style:solid;
border-width:5px;
position: absolute;
}
</style>
<script>
$(document).ready(function(){
var b = new ball(1, 1, 10, 10);
for(i = 0; i < 1000; i++)
b.moveBall();
});
function ball(xPos, yPos, xVel, yVel)
{
this.xPos = xPos;
this.yPos = yPos;
this.xVel = xVel;
this.yVel = yVel;
this.rightBound = false
this.leftBound = false;
this.upBound = false;
this.downBound = false;
this.width = 50;
this.height = 50;
this.moveBall = moveBall;
function moveBall()
{
var h = 500;
var w = 700;
//detect if it is at x bounds
if(this.xPos + this.width + this.xVel > w)
{this.rightBound = true;}
else if(this.xPos + this.xVel < -1)
this.leftBound = true;
else
{
this.rightBound = false;
this.leftBound = false;
}
//detect if it is at y bounds
if(this.yPos + this.height + this.yVel > h)
{this.downBound = true;}
else if(this.yPos + this.yVel < -1)
this.upBound = true;
else
{
this.upBound = false;
this.downBound = false;
}
//handle velocity changes for bounds
//so you switch the x direction if x bound is met, same for y
if(this.rightBound || this.leftBound)
this.xVel *= -1;
if(this.upBound || this.downBound)
this.yVel *= -1;
//now give motion
this.xPos += xVel;
this.yPos += yVel;
//now draw
$(".ball").animate({
left:this.xPos + 'px',
top:this.yPos + 'px'
}, 150).text(this.xPos + "," + this.yPos);
}
}
</script>
</head>
<body>
<div class="boundary">
<div class="ball"></div>
</div>
</body>
</html>
奇怪的是,它似乎从一开始就自动将最终值 10,001、10,001(假设它从不改变方向)作为 (x,y) 坐标。任何可以为我指明正确方向的东西都将不胜感激!对不起,如果这是一些基本错误,我试图确保它不是但有时他们会漏掉!