canvas模拟重力效果

总结

  1. 速度和加速度是动画的基础元素,其中两者都是向量,包括了一个重要因素:方向。
  2. 要学会应用 分解 和 合成 ,将速度或加速度分解到x、y轴上,然后将每条轴上的加速度或速度相加,然后再分别与物体的位置坐标相加。 

附录:

总要公式:

(1)将角速度分解为x、y轴上的速度向量

vx = speed * Math.cos(angle)

vy = spedd * Math.sin(angle)

(2)将角加速度分解为x、y轴上的加速度

ax = force * Math.cos(angle)

ay = force * Math.sin(angle)

(3)将加速度加入速度向量

vx += ax;

vy += ay;

(4)将速度向量加入位置坐标

object.x += vx;

object.y += vy;

 下面是具体实现代码

var canvas = document.getElementById("canvas");
var cxt = canvas.getContext("2d");
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var g=0.3;
var bounce=-0.7;
function Ball(x, y, radius, speed) {
this.x = x;
this.y = y;
this.radius = radius;
this.speed = speed;
}

function Getrandom(min, max) {
return(Math.random() * (max - min) + min+1);
}
var ball = [];
document.getElementById("btn").onclick = function() {
var speed = {
x: 0,
y: 3
};
x=Getrandom(30,canvas.width-30);
ball.push(new Ball(x, 0, 10, speed))
}
function drawBall() {
cxt.clearRect(0, 0, canvas.width, canvas.height);
for(var i = 0; i < ball.length; i++) {
var b = ball[i];
cxt.beginPath();
b.x +=b.speed.x;
b.y += b.speed.y;
if(b.y>=canvas.height-b.radius*2){
b.y=canvas.height-b.radius*2;
b.speed.y*=bounce;
}

b.speed.y+=g;
b.y+=b.speed.y;
cxt.arc(b.x, b.y, b.radius, 0, Math.PI * 2, true);
cxt.fillStyle = "red";
cxt.fill();
cxt.closePath();
}
requestAnimationFrame(drawBall);
}
drawBall();

  

原文地址:https://www.cnblogs.com/myzsy/p/6104515.html