我的概念相当简单。用一种方式动画一个图像,然后让它回来。
var xPos = 10;
function main(){
window.requestAnimationFrame(main);
var canvas = document.getElementById("myCanvas");
var c = canvas.getContext("2d");
//Initialize images
var img = new Image();
img.src = "goomba.png";
c.clearRect(0,0,500,500);
c.drawImage(img,xPos,10);
//increment coordinates
if(xPos <= 250){
xPos+=2;
}
else if(xPos >= 250){
xPos-=2;
}
}
window.requestAnimationFrame(main);我已经知道我的代码有什么问题了。当xPos超过250时,则第二个if语句变为真。然而,一旦它低于250,第一个如果再次变为真。所以我知道问题出在哪里,只是不知道怎么解决。任何帮助都是非常感谢的!
发布于 2013-02-05 15:42:50
有一个速度变量(正是右,负是左,振幅是改变每个循环的像素数):
var xVelocity = 2;并使用它来确定要添加到xPos each循环中的内容:
xPos += xVelocity;然后根据xVelocity和xPos设置它,这样图像就会“反弹”:
if(xVelocity > 0){
if(xPos > 250){
xVelocity = -2;
}
} else {
if(xPos < 10){
xVelocity = 2;
}
}发布于 2013-02-05 15:51:21
http://jsbin.com/uweyam/1/edit
这就是你想要的吗?还是你想把它停在左边的边缘?
UPD.:你也可以让它像这样反弹- http://jsbin.com/uweyam/4/edit
https://stackoverflow.com/questions/14711112
复制相似问题