我想将一个球(带有图像)扔到一个二维场景中,并在它到达一定距离时检查它是否发生碰撞。但我不能让它正确地“飞”起来。似乎这个问题已经被问了一百万次了,但是我发现的越多,我就越困惑。现在我遵循了这个答案,但看起来,球的行为与我预期的非常不同。事实上,它移动到我的画布的左上角并且变得太小太快了——当然我可以通过将 vz 设置为 0.01 或类似的值来调整它,但是我根本看不到球……
这是我的对象(简化)/链接到感兴趣的完整来源。重要的部分是 update() 和 render()
var ball = function(x,y) {
this.x = x;
this.y = y;
this.z = 0;
this.r = 0;
this.src = 'img/ball.png';
this.gravity = -0.097;
this.scaleX = 1;
this.scaleY = 1;
this.vx = 0;
this.vy = 3.0;
this.vz = 5.0;
this.isLoaded = false;
// update is called inside window.requestAnimationFrame game loop
this.update = function() {
if(this.isLoaded) {
// ball should fly 'into' the scene
this.x += this.vx;
this.y += this.vy;
this.z += this.vz;
// do more stuff like removing it when hit the ground or check for collision
//this.r += ?
this.vz += this.gravity;
}
};
// render is called inside window.requestAnimationFrame game loop after this.update()
this.render = function() {
if(this.isLoaded) {
var x = this.x / this.z;
var y = this.y / this.z;
this.scaleX = this.scaleX / this.z;
this.scaleY = this.scaleY / this.z;
var width = this.img.width * this.scaleX;
var height = this.img.height * this.scaleY;
canvasContext.drawImage(this.img, x, y, width, height);
}
};
// load image
var self = this;
this.img = new Image();
this.img.onLoad = function() {
self.isLoaded = true;
// update offset to spawn the ball in the middle of the click
self.x = this.width/2;
self.y = this.height/2;
// set radius for collision detection because the ball is round
self.r = this.x;
};
this.img.src = this.src;
}
我还想知道,当使用 requestAnimationFrame 以约 60fps 的速度渲染画布时,哪些速度参数应该是合适的,以获得“自然”的飞行动画
如果有人能指出我正确的方向(当然还有解释逻辑的伪代码),我将不胜感激。
谢谢