【发布时间】:2018-12-04 08:42:05
【问题描述】:
我正在尝试了解如何在我的动画中添加一些物理学,例如重力和风。我无法完全理解如何让这个球像有重力一样弹跳……每次更新我都在累积力,将其应用于速度,然后清除力。但我能想到让它反弹的唯一方法是改变 Y 方向..但它会继续前进,直到它到达顶部。我有什么明显的遗漏吗?任何建议表示赞赏。感谢阅读
var C, canvas, context = null;
var gravity = {x:0, y:1};
var wind = {x:0.4, y:0};
var height = 140;
var width = 300;
function Ball(x,y,w,h) {
var ball = this;
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.xVelocity = 0;
this.yVelocity = 0;
this.xDirection = 1;
this.yDirection = 1;
this.update = function() {
ball.applyForce(gravity);
//ball.applyForce(wind);
ball.x += (ball.xVelocity * ball.xDirection);
ball.y += (ball.yVelocity * ball.yDirection);
if((ball.x + ball.w) >= width) {
//ball.xDirection = -1;
ball.x = width - ball.w / 2 ;
ball.xVelocity = -ball.xVelocity
} else if(ball.x <= 0) {
//ball.xDirection = 1;
ball.xVelocity = ball.xVelocity
}
if((ball.y + ball.h) >= height) {
//ball.yDirection = -1;
ball.y = height - ball.w;
ball.yVelocity = -ball.yVelocity
} else if(ball.y <= 0) {
//ball.yDirection = 1;
ball.yVelocity = ball.yVelocity
}
//ball.clearForces();
}
this.draw = function() {
context.beginPath();
context.arc(ball.x,ball.y,ball.w,0,2*Math.PI);
context.stroke();
}
this.applyForce = function(force) {
ball.xVelocity += force.x;
ball.yVelocity += force.y;
}
this.clearForces = function(force) {
ball.xVelocity = 0;
ball.yVelocity = 0;
}
}
function Canvas( ) {
var CV = this;
var balls = new Array();
balls.push(new Ball(100, 10, 10, 10));
this.loop = function() {
CV.update();
CV.draw();
window.requestAnimationFrame(CV.loop);
}
this.update = function() {
for(var i=0; i<balls.length; i++) {
balls[i].update();
}
}
this.draw = function() {
context.clearRect(0, 0, width, height);
for(var i=0; i<balls.length; i++) {
balls[i].draw();
}
}
}
canvas = document.getElementById("canvas");
context = canvas.getContext("2d");
C = new Canvas( );
C.loop();
#canvas {border:1px solid #d4d4d4; }
<canvas id="canvas" width="300" height="140"></canvas>
【问题讨论】:
-
当你撞到地板时不要改变方向,而是否定速度:
ball.yVelocity = -ball.yVelocity -
@Matt L. 谢谢,但我对此并不走运。这是我做的顺序吗?我编辑了 sn-p 并尝试了。我应该指出我确实尝试过反转速度。我得到的最好结果是球被卡在地上,但它从来没有反弹回来。现在请看 sn-p,球一直在前进。
-
对不起,这不会直接帮助,但它似乎很相关。 uselesspickles.com/jsballs(它适用于 IE6,就像 10 年前写的一样)
-
尝试将球的位置重置到地板上并取消速度。在翻转速度后的帧上,您仍然低于阈值
-
@Matt L. 感谢马特,我将它添加到 sn-p 但它粘在底部而不是向上反弹。不过,这似乎是朝着正确方向迈出的一步。