模拟类似于尘埃粒子的运动

时间:2011-11-29 06:19:43

标签: javascript jquery timer physics

我尝试过使用css和animate的setInterval循环。两种运动方式都包括来自oldpos1的微小运动 - >没有随机曲线移动的newpos1,但是jQuery动画却出现了缓动,但只是在随机生成的1-3像素之间,这不是我想要的 。 问题出在setInterval的时钟中,只有线性时间单位才会流动吗?

我应该从哪里开始,在jQuery中存在以下图片?

我想做什么:

  1. 道奇行为:

    A,B - 粒子

    AB1 - 常见的闪避区域,只有一定的数量

  2. enter image description here

    2运动:

    Av,Bv - 随机循环运动

    Aacc,Bacc - 发生微小的随机加速度(在标记为更加相称的虚线的图像上)

    enter image description here

1 个答案:

答案 0 :(得分:1)

我不会依赖jQuery' animate因为你的情况比较特殊......相反,使用"游戏循环模式":有一个游戏对象保持不变一组粒子,它们被移动(并碰撞......),然后定期绘制。

这是一个基本结构:

function Particle(x, y) {
    this.x = x;
    this.y = y;
    this.speed = 0; // in pixels per second
    this.direction = 0; // in radians per second
}

Particle.prototype.move = function(d_time) {
    this.x += Math.cos(this.direction) * this.speed;
    this.y += Math.sin(this.direction) * this.speed;
}

Particle.prototype.draw = function() {
    // either set the position of a DOM object belonging to this particle
    // or draw to a canvas
}

function Game() {
    this.particles = Array();

    this.MS_PER_FRAME = 20; // in milliseconds
    this.D_TIME = 1000.0 / this.MS_PER_FRAME;
}

Game.prototype.tick = function() {
    $.each(this.particles, function(_, particle) {
        particle.move(this.D_TIME);
        particle.draw();
    })
}

Game.prototype.go = function() {
    setInterval(this.tick, this.MS_PER_FRAME)
})

然后您可以根据需要操纵粒子的速度和方向,也可以通过引入其他成员d_speed(加速度)和d_direction左右。