Simulating movement similar to dust particles

回眸只為那壹抹淺笑 提交于 2019-12-22 18:43:00

问题


I've tried a setInterval loop with css and animate. Both ways of movement consists of tiny movement from oldpos1 -> newpos1 with no random curve movement, easing however occured with jQuery animate but only between randomly generated 1-3 pixels, which is not what I want . Does the problem lies in setInterval's clock, where only linear time units flow?

Where should I start, to make below images exist in jQuery?

What I would like to do:

  1. Dodge behaviour:

    A, B - particle

    AB1 - common dodge area, only certain amount

2 Movement:

Av, Bv - random circular movement

Aacc, Bacc - where the tiny random acceleration occurs (on image marked as more condenced dashed lines)


回答1:


I would not rely on jQuery's animate for this as your case is rather special ... instead, use the "game loop pattern": Have a game object which keeps a collection of particles, which are moved (and collided ...) and then drawn in regular intervals.

Here's a basic structure:

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)
})

Then you can manipulate speed and direction of particles as you like, maybe by introducing additional members d_speed (acceleration) and d_direction or so.



来源:https://stackoverflow.com/questions/8306717/simulating-movement-similar-to-dust-particles

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!