我有一个通过画布移动图像的功能。
run子函数在每个帧上运行,当它返回true时结束。
问题在于移动速度取决于你拥有的fps数量。
我希望能够放置一个每秒像素的变量,因此无论你有多少fps,图像都会以相同的速度移动。
this.MoveImage = function(opts){
var image = opts.image;
var x1 = opts.x1;
var y1 = opts.y1;
var x2 = opts.x2;
var y2 = opts.y2;
var angle = Math.atan2(y2-y1, x2-x1);
var speed = opts.speed;
var xDirection = null;
var yDirection = null;
if(x1 < x2) xDirection = "positive";
else if(x1 > x2) xDirection = "negative";
if(y1 < y2) yDirection = "positive";
else if(y1 > y2) yDirection = "negative";
this.run = function(){
x1 += speed*Math.cos(angle);
y1 += speed*Math.sin(angle);
context.drawImage(image, x1, y1);
if(compare(x1, x2, xDirection) && compare(y1, y2, yDirection)){
return true;
}
}
function compare(n1, n2, direction){
if(n1 >= n2 && direction == "positive") return true;
else if(n1 <= n2 && direction == "negative") return true;
else if(n1 == n2 && direction == null) return true;
}
}