Как изменить класс Enemy, чтобы он преследовал игрока в объектно-ориентированной игре на JavaScript?CSS

Разбираемся в CSS
Ответить
Anonymous
 Как изменить класс Enemy, чтобы он преследовал игрока в объектно-ориентированной игре на JavaScript?

Сообщение Anonymous »

Я пытаюсь создать игру на HTML, CSS и JavaScript. Я начал следовать руководству FreeCodeCamp: . Учебное пособие было посвящено игре с боковой прокруткой (без гравитации для персонажей, если вам интересно), но я пытаюсь создать игру с видом сверху, в которой враги преследуют игрока. Мне удалось управлять управлением игроком влево/вправо, но я не знаю, как изменить поведение врага, чтобы он преследовал игрока. Я новичок в ООП и разработке игр с использованием JavaScript.
Вот код (вражеский класс):

Код: Выделить всё

class Enemy {
constructor(game){
this.game = game;
this.x = this.game.width;
this.speed = Math.random() * -1.5 - 0.5;
this.markedForDeletion = false;
this.lives = 5;
this.score = this.lives;
}
update(){
this.x += this.speed;

if (this.x + this.wodth > 0) this.markedForDeletion = true;
}
draw(context){
context.fillStyle = 'red';
context.fillRect(this.x, this.y, this.width, this.height);
context.fillStyle = 'black';
context.font = '20px Helvetica'
context.fillText(this.lives, this.x, this.y);
}
}
class Angler1 extends Enemy {
constructor(game){
super(game);
this.width = 228 * 0.2;
this.height = 169 * 0.2;
this.y = Math.random() * (this.game.height * 0.9 - this.height);

}
}
Класс игрока:

Код: Выделить всё

class Player {
constructor(game){
this.game = game;
this.width = 80;
this.height = 120;
this.x = 20;
this.y = 100;
this.speedX = 3;
this.speedY = 0;
this.maxSpeed = 3;
this.projectiles = [];
}
update(){
if(this.game.keys.includes('w')) this.speedY = -this.maxSpeed;
else if (this.game.keys.includes('s')) this.speedY = this.maxSpeed;
else if (this.game.keys.includes('a')) this.speedX = -this.maxSpeed;
else if (this.game.keys.includes('d')) this.speedX = this.maxSpeed;
else {
this.speedY = 0;
this.speedX = 0;
}
this.y += this.speedY;
this.x += this.speedX;
//handle projectiles
this.projectiles.forEach(projectile => {
projectile.update();
});
this.projectiles = this.projectiles.filter(projectile => !projectile.markedForDeletion);
}
draw(context){
context.fillStyle = 'black';
context.fillRect(this.x, this.y, this.width, this.height);
this.projectiles.forEach(projectile => {
projectile.draw(context);
});
}
shootTop(){
if (this.game.ammo > 0){
this.projectiles.push(new Projectile(this.game, this.x + 80, this.y + 30));
this.game.ammo--;
}
}
}
игровой класс и игровой цикл:

Код: Выделить всё

class Game {
constructor(width, height){
this.width = width;
this.height = height;
this.player = new Player(this);
this.input = new InputHandler(this);
this.ui = new UI(this);
this.keys = [];
this.enemies = [];
this.enemyTimer = 0;
this.enemyInterval = 1000;
this.ammo = 20;
this.maxAmmo = 50;
this.ammoTimer = 0;
this.ammoInterval = 500;
this.gameOver = false;
this.score = 0;
this.winningScore = 10;
this.gameTime = 0;
this.timeLimit = 20000;
}
update(deltaTime){
if(!this.gameOver) this.gameTime += deltaTime;
if(this.gameTime > this.timeLimit) this.gameOver = true;
this.player.update();
if (this.ammoTimer > this.ammoInterval){
if (this.ammo < this.maxAmmo) this.ammo++;
this.ammoTimer = 0;
} else {
this.ammoTimer += deltaTime;
}
this.enemies.forEach(enemy => {
enemy.update();
if (this.checkCollision(this.player, enemy)){
enemy.markedForDeletion = true;
}
this.player.projectiles.forEach(projectile =>  {
if (this.checkCollision(projectile, enemy)){
enemy.lives--;
projectile.markedForDeletion = true;
if(enemy.lives  this.winningScore) this.gameOver = true;
}
}
})
});
this.enemies = this.enemies.filter(enemy => !enemy.markedForDeletion);
if(this.enemyTimer > this.enemyInterval && this.gameOver === false){
this.addEnemy();
this.enemyTimer = 0;
} else {
this.enemyTimer += deltaTime;
}
}
draw(context){
this.player.draw(context);
this.ui.draw(context);
this.enemies.forEach(enemy => {
enemy.draw(context);
});
}
addEnemy(){
this.enemies.push(new Angler1(this));
}
checkCollision(rect1, rect2){
return (    rect1.x < rect2.x + rect2.width &&
rect1.x + rect1.width > rect2.x &&
rect1.y < rect2.y + rect2.height &&
rect1.height + rect1.y > rect2.y)
}
}

const game = new Game(canvas.width, canvas.height);
let lastTime = 0;
//animation loop
function animate(timeStamp){
const deltaTime = timeStamp - lastTime;
lastTime = timeStamp;
ctx.clearRect(0, 0, canvas.width, canvas.height);
game.update(deltaTime);
game.draw(ctx);
requestAnimationFrame(animate);

}
(некоторые несвязанные классы, например класс снаряда, были удалены для экономии места)


Подробнее здесь: https://stackoverflow.com/questions/799 ... programmin
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «CSS»