game: extract getDirection

This commit is contained in:
He4eT 2025-06-06 22:58:31 +02:00
commit 168aba5b52

62
game.js
View file

@ -264,55 +264,54 @@ function spawn() {
} }
function moveEnemies() { function moveEnemies() {
enemies.forEach((enemy) => ({ enemies.forEach((enemy) =>
'point': () => {}, ({
'fidget': () => {}, point: () => {},
'bounce': () => { fidget: () => {},
bounce: () => {
const speed = 1 const speed = 1
const current = enemy.positions[0] const current = enemy.positions[0]
const previous = enemy.positions[1] const previous = enemy.positions[1]
/**/ let d = getDirection(previous, current)
let dx = current.x - previous.x
let dy = current.y - previous.y
const length = Math.hypot(dx, dy) || 1 dx = d.x * speed
dx /= length dy = d.y * speed
dy /= length
/**/
let newX = current.x + dx * speed let newX = current.x + dx
let newY = current.y + dy * speed let newY = current.y + dy
if (newX < arena.bounds.left || newX > arena.bounds.right) { if (newX < arena.bounds.left || newX > arena.bounds.right) {
dx = -dx dx = -dx
newX = current.x + dx * speed newX = current.x + dx
} }
if (newY < arena.bounds.top || newY > arena.bounds.bottom) { if (newY < arena.bounds.top || newY > arena.bounds.bottom) {
dy = -dy dy = -dy
newY = current.y + dy * speed newY = current.y + dy
} }
enemy.positions = [ enemy.positions = [
{ x: newX, y: newY }, { x: newX, y: newY },
{ x: current.x, y: current.y } { x: current.x, y: current.y },
] ]
}, },
'zombie': () => { zombie: () => {
const speed = 0.5 const speed = 0.5
const current = enemy.positions[0]
const target = player.position
const currentPosition = enemy.positions[0] const d = getDirection(current, target)
const dx = player.position.x - currentPosition.x
const dy = player.position.y - currentPosition.y
const dist = Math.hypot(dx, dy)
enemy.positions = [{ enemy.positions = [
x: currentPosition.x + (dx / dist) * speed, {
y: currentPosition.y + (dy / dist) * speed, x: current.x + d.x * speed,
}] y: current.y + d.y * speed,
}, },
}[enemy.type]())) ]
},
})[enemy.type](),
)
} }
function checkColisions() { function checkColisions() {
@ -429,6 +428,17 @@ function rnd(from, to) {
return Math.floor(Math.random() * (to - from + 1)) + from return Math.floor(Math.random() * (to - from + 1)) + from
} }
function getDirection(from, to) {
const dx = to.x - from.x
const dy = to.y - from.y
const distance = Math.hypot(dx, dy) || 1
return {
x: dx / distance,
y: dy / distance,
}
}
/* Constants */ /* Constants */
/* Screen */ /* Screen */