Skip to content

Commit

Permalink
chore: make enemy follow player
Browse files Browse the repository at this point in the history
  • Loading branch information
remarkablemark committed Jan 21, 2025
1 parent be25094 commit 8cafea1
Show file tree
Hide file tree
Showing 5 changed files with 33 additions and 10 deletions.
1 change: 1 addition & 0 deletions src/constants/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './tags'
3 changes: 3 additions & 0 deletions src/constants/tags.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export enum Tag {
'player' = 'player',
}
18 changes: 17 additions & 1 deletion src/gameobjects/enemy.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,21 @@
import { Tag } from '../constants'
import { ghosty } from '../sprites'

const ENEMY_SPEED = 200

export function addEnemy(x: number, y: number) {
return add([ghosty, pos(x, y), anchor('center')])
const enemy = add([ghosty, pos(x, y), anchor('center')])

enemy.onUpdate(() => {
const player = get(Tag.player)[0]

if (!player) {
return
}

const dir = player.pos.sub(enemy.pos).unit()
enemy.move(dir.scale(ENEMY_SPEED))
})

return enemy
}
12 changes: 11 additions & 1 deletion src/gameobjects/player.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
import { Tag } from '../constants'
import { addCursorKeys } from '../events'
import { bean } from '../sprites'

export function addPlayer(x = center().x, y = center().y) {
return add([bean, pos(x, y), rotate(0), anchor('center')])
const player = add([bean, pos(x, y), rotate(0), anchor('center'), Tag.player])

player.onUpdate(() => {
player.angle += 120 * dt()
})

addCursorKeys(player)

return player
}
9 changes: 1 addition & 8 deletions src/scenes/game.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,8 @@
import { addCursorKeys } from '../events'
import { addEnemy, addPlayer } from '../gameobjects'
import { Scene } from '../types'

scene(Scene.game, () => {
const player = addPlayer()

player.onUpdate(() => {
player.angle += 120 * dt()
})

addCursorKeys(player)
addPlayer()

onClick(() => addKaboom(mousePos()))

Expand Down

0 comments on commit 8cafea1

Please sign in to comment.