javascript - How to move an object diagonally and in zigzag? -


i created algorithm move particle diagonally , works fine using angle. basically, do:

this.x += this.speed * math.cos(this.angle * math.pi / 180); this.y += this.speed * math.sin(this.angle * math.pi / 180); this.draw(); 

how can combine zigzag movement?

i recommend calculating lateral deviation normal path or amplitude given by

// triangle wave @ position t period p: function amplitude(t, p) {   t %= p;   return t > p * 0.25 ? t < p * 0.75 ? p * 0.5 - t : t - p : t; } 

where t set length of traveled path, , p period of 'zigzag' triangle wave pattern.

given amplitude , previous position, can compute next position moving ahead described original code , adding lateral deviation our position:

  var amplitude = amplitude(distance, p) - this.amplitude(previous_distance, p);   this.x += amplitude * math.sin(this.angle * math.pi/180);   this.y -= amplitude * math.cos(this.angle * math.pi/180); 

a complete example 2 movable objects, 1 moving 'normally' , 1 following 'zigzag' pattern:

function movable(x, y, speed, angle, period) {    this.x = x;    this.y = y;    this.speed = speed;    this.angle = angle;    this.period = period;    this.distance = 0;  }    movable.prototype.movediagonal = function() {    this.distance += this.speed;    this.x += this.speed * math.cos(this.angle * math.pi / 180);    this.y += this.speed * math.sin(this.angle * math.pi / 180);  }    movable.prototype.amplitudezigzag = function() {    var p = this.period, d = this.distance % p;    return d > p * 0.25 ? d < p * 0.75 ? p * 0.5 - d : d - p : d;  }    movable.prototype.movezigzag = function() {    var amplitude1 = this.amplitudezigzag();    this.movediagonal();    var amplitude2 = this.amplitudezigzag();        var amplitude = amplitude2 - amplitude1;    this.x -= amplitude * math.sin(this.angle * math.pi/180);    this.y += amplitude * math.cos(this.angle * math.pi/180);  }    movable.prototype.draw = function(context) {    context.beginpath();    context.arc(this.x, this.y, 1, 0, 2 * math.pi);    context.stroke();  }    var canvas = document.getelementbyid("canvas");  var context = canvas.getcontext("2d");    var m1 = new movable(0, 0, 2, 0, 50);  var m2 = new movable(0, 0, 2, 0, 50);    (var = 0; < 1000; ++i) {    m1.angle += math.cos(i * math.pi/180);    m2.angle += math.cos(i * math.pi/180);    m1.movediagonal();    m2.movezigzag();    m1.draw(context);    m2.draw(context);  }
<canvas id="canvas" width="600" height="200"></canvas>


Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -