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

标签 javascript jquery timer physics

我尝试了一个带有 css 和动画的 setInterval 循环。两种移动方式都包括从 oldpos1 -> newpos1 的微小移动,没有随机曲线移动,但是缓动发生在 jQuery animate 中,但仅在随机生成的 1-3 个像素之间,这不是我想要的 . 问题是否出在setInterval的时钟上,那里只有线性时间单位流动?

我应该从哪里开始,让下面的图像存在于 jQuery 中?

我想做什么:

  1. 闪避行为:

    A, B - 粒子

    AB1 - 普通闪避区域,只有一定数量

enter image description here

2 运动:

Av, Bv - 随机圆周运动

Aacc、Bacc - 微小的随机加速度发生的地方(在图像上标记为更浓缩的虚线)

enter image description here

最佳答案

我不会依赖 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 左右。

关于javascript - 模拟类似于尘埃粒子的运动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8306717/

相关文章:

java - 计时器到分钟 : seconds : hundreds of seconds

javascript - 与定时器异步运行

php - jquery post() 不以动态形式工作

javascript - 获取 jQuery 对话框中的底层元素

javascript - 鼠标悬停事件委托(delegate)

javascript - 仅在选择选项发生更改后获取输入值

java - 当 Swing Timer 启动时,ActionListener 类不断重复

javascript - 如何构建在非全局区域设置中工作的 'moment' 函数?

Javascript:以编程方式触发 onbeforeunload/onunload 事件

jquery - 将相同的随机类应用于指定的每个元素