Преследование
by twobomb three
HTML
<canvas id="canvas"></canvas>
CSS
body,html{
margin:0;
height:100%;
}
JavaScript
var canvas = document.querySelector("canvas");
canvas.width = document.body.offsetWidth;
canvas.height = document.body.offsetHeight;
var ctx = canvas.getContext("2d");
var lastTime = null;
var enemies = [];
var player = {
x:0,
y:0,
w:20,
h:20,
moveToX:0,
moveToY:0,
speed:200,
draw:function(){
ctx.fillStyle = "blue";
ctx.fillRect(this.x,this.y,this.w,this.h);
ctx.beginPath();
ctx.moveTo(this.x+this.w/2,this.y+this.h/2);
ctx.lineTo(this.moveToX,this.moveToY);
ctx.stroke();
ctx.beginPath();
ctx.arc(this.moveToX,this.moveToY,5,0,Math.PI*2);
ctx.stroke();
},
move:function(deltaTime){
var angle = getAngle(this.x+this.w/2,this.y+this.h/2,this.moveToX,this.moveToY);
this.x += (this.speed * deltaTime)* Math.cos(angle);
this.y += (this.speed * deltaTime)* Math.sin(angle);
if(getDist(this.x+this.w/2,this.y+this.h/2,this.moveToX,this.moveToY) <= 3){
this.moveToX = Math.random() * canvas.width;
this.moveToY = Math.random() * canvas.height;
}
}
};
function enemy(x,y,speed){
this.x = x;
this.y = y;
this.w = 10;
this.h = 10;
this.speed = speed || 100;
this.move = function(deltaTime){
var angle = getAngle(this.x,this.y,player.x,player.y);
this.x += (this.speed * deltaTime)* Math.cos(angle);
this.y += (this.speed * deltaTime)* Math.sin(angle);
};
this.draw = function(){
ctx.fillStyle = "red";
ctx.fillRect(this.x,this.y,this.w,this.h);
};
this.isCollision = function(obj){
return this.x < obj.x+obj.w && this.x+this.w > obj.x &&
this.y < obj.y+obj.h && this.y+this.h > obj.y;
}
};
(function(){
var deltaTime = (Date.now() - (lastTime || Date.now()))/1000;
lastTime = Date.now();
ctx.clearRect(0,0,canvas.width,canvas.height);
player.draw();
player.move(deltaTime);
var countEnemy = 5;
while(enemies.length < countEnemy)
enemies.push(new enemy(Math.random() * canvas.width,Math.random() *...