之后的函数是用户绘制canvas的背景,依据的属性是用户设定的背景色,canvas的宽度和高度。
/* 更新小球状态 */
var updateBallState = function(ballObj, canvasWidth, canvasHeight, gravityValue, friction) {
ballObj.currentX = ballObj.nextX; ballObj.currentY = ballObj.nextY; ballObj.nextX = ballObj.currentX + ballObj.dx; ballObj.nextY = ballObj.currentY + ballObj.dy;
/* 测试对墙壁产生是否X轴碰撞 */
if (ballObj.nextX < ballObj.radius) { ballObj.nextX = ballObj.radius; ballObj.dx = Math.max(0, (ballObj.dx + ((1 - ballObj.elasticity) * Math.abs(ballObj.dx))) * -1 - 1); } else if ((ballObj.nextX + ballObj.radius) > parseInt(canvasWidth)) { ballObj.nextX = parseInt(canvasWidth) - ballObj.radius; ballObj.dx = Math.min(0, (ballObj.dx - ((1 - ballObj.elasticity) * Math.abs(ballObj.dx))) * -1 + 1); }
/* 水平运动时受摩擦力影响 */ else if (ballObj.currentY >= (parseInt(canvasHeight) - ballObj.radius)) {
if (ballObj.dx > 0) { ballObj.dx = Math.max(0, ballObj.dx - (ballObj.dx * friction) - 0.01); } else if (ballObj.dx < 0) { ballObj.dx = Math.min(0, ballObj.dx - (ballObj.dx * friction) + 0.01); }
}
/* 测试对墙壁产生是否Y轴碰撞 */ if (ballObj.nextY < ballObj.radius) { ballObj.nextY = ballObj.radius; ballObj.dy = Math.max(0, (ballObj.dy + ((1 - ballObj.elasticity) * Math.abs(ballObj.dy))) * -1 - 1); } else if ((ballObj.nextY + ballObj.radius) > parseInt(canvasHeight)) { ballObj.nextY = parseInt(canvasHeight) - ballObj.radius; ballObj.dy = Math.min(0, (ballObj.dy - ((1 - ballObj.elasticity) * Math.abs(ballObj.dy))) * -1 + 1);
} else { ballObj.dy = ballObj.dy + gravityValue; }
};
接着是核心函数,updateBallState。该函数的作用是通过小球半径,canvas宽高等参数,判断小球是否和墙壁产生碰撞。并根据对四个不同墙壁的碰撞分别使用不同的处理方法。具体过程如下:
1.首先把上次记录的nextX和nextY设置为现在的currentX和currentY,更新了现在小球所处的位置。
2.计算小球的nextX和nextY,这两个参数将会决定小球下次所处的位置。
3.如果ballObj.nextX < ballObj.radius,册小球于左边的墙壁碰撞,此时把nextX设置为小球半径的值,是为了让小球在完全和墙壁发生碰撞(和墙壁距离为0)之后,再反弹。
之后改变小球的速度:
ballObj.dx = Math.max(0, (ballObj.dx + ((1 - ballObj.elasticity) * Math.abs(ballObj.dx))) * -1 - 1); (编辑:威海站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|