JSFiddle - React, Tailwind, and code Playground
by Kirill
HTML
<canvas id="c" width=500 height=500></canvas>
JavaScript
var c = document.getElementById("c");
var ctx = c.getContext("2d");
c.onclick = (function(event) {
var x = event.pageX - c.offsetLeft,
y = event.pageY -c.offsetTop;
t.push(new tower(x,y));
});
var path = [[10,10,10,30,35,60,80,100],[10,30,40,50,80,80,70,100]];
function drawPath(p) {
ctx.fillStyle="green";
ctx.fillRect(0,0,500,500);
ctx.beginPath();
ctx.strokeStyle="white";
ctx.lineWidth = 25;
ctx.moveTo(0,0);
for(i=0;i<p[0].length;i++) {
ctx.lineTo(p[0][i]*5, p[1][i]*5);
}
ctx.stroke();
}
function vl(ax,ay,bx,by) {
//Vector length
return Math.sqrt(Math.pow(ax-bx,2) + Math.pow(ay-by,2));
}
//drawPath(path);
function expl(x,y,r) {
this.x = x;
this.y = y;
this.r = r;
this.draw = function() {
ctx.beginPath();
ctx.fillStyle="red";
ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI, false);
ctx.fill();
};
}
function truck(x,y,speed) {
this.x = x;
this.y = y;
this.speed = speed;
this.path = path;
this.step = 0;
this.health = 200;
this.move = function(i) {
var tx = this.path[0][this.step]*5;
var ty = this.path[1][this.step]*5;
var distance = vl(this.x,this.y,tx,ty);
this.a = Math.acos((ty-this.y)/vl(this.x,this.y,tx,ty));
if(tx>this.x) this.a = -this.a;
this.draw();
this.x+=((tx-this.x)*this.speed)/distance;
this.y+=((ty-this.y)*this.speed)/distance;
if (Math.abs(this.x-tx)<this.speed && Math.abs(this.y-ty)<this.speed) {
this.step++;
}
if(this.step==this.path[0].length) w.mob.splice(i,1);
};
this.draw = function () {
ctx.beginPath();
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate(this.a);
ctx.fillStyle="blue";
ctx.fillRect (-5,-8,10,16);
ctx.fillStyle="black";
ctx.arc(0, 0, 3, 0, 2 * Math.PI, false);
ctx.fillRect (-2,0,4,12);
ctx.fillRect (-7,-7,2,14);
ctx.fillRect (5,-7,2,14);
...