JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="myCanvas" width="320" height="240" style="width:640px;"></canvas>
JavaScript
window.requestAnimFrame = (function(callback) {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
function(callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
var spawner = {
position: {
x: 0,
y: 0,
get: function (){
return {
x: Math.round(this.x * 1000),
y: Math.round(this.y * 1000)
}
}
}, velocity: {
x: 0,
y: 0
}, acceleration: {
x: 0,
y: 0,
normalize: function (max){
var a = Math.sqrt(this.x * this.x + this.y * this.y);
if (a != 0) {
this.x = (this.x / a) * max;
this.y = (this.y / a) * max;
}
}
}, path: [
[85, 220], [85, 40], [250, 220], [250, 40]
], target: {
x: 0,
y: 0
}, tolerance : 20
, nextPoint: 0
, update: function (){
var delta = {
x: this.target.x - this.position.x,
y: this.target.y - this.position.y,
dist: function (){
return Math.sqrt(this.x * this.x + this.y * this.y);
}
};
this.acceleration.x = delta.x;
this.acceleration.y = delta.y;
if (delta.dist() < this.tolerance) {
this.nextPoint++;
if (this.nextPoint > this.path.length-1){
this.nextPoint = 0;
this.position.x = this.path[0][0];
this.position.y = this.path[0][1];
}
this.target.x = this.path[this.nextPoint][0];
this.target.y = this.path[this.nextPoint][1];
this.velocity.x *= 0;
this.velocity.y *= 0;
}
this.acceleration.normalize(.02);
this.velocity.x += this.acceleration.x;
this.velocity.y += this.acceleration.y;
this.position.x += this.velocity.x;
this.position.y += this.velocity.y;
this.acceleration.x = 0;
this.acceleration.y = 0;
}, init: function (){
this.target.x = this.path[this.nextPoint][0];
this.target.y = this.path[this.nextPoint][1];
this.position.x = this.target.x;
this.position.y = this.target.y;
}
};
spawner.init();
var canvas = document.getElementById('myCanvas');
var ctx =...