Add events

This commit is contained in:
Bill Rossi 2025-06-06 21:04:58 -04:00
parent b7e86ce8ac
commit 9fb09c1244
4 changed files with 44 additions and 4 deletions

View File

@ -43,10 +43,15 @@
"id":1,
"name":"",
"properties":[
{
"name":"color",
"type":"string",
"value":"red"
},
{
"name":"event",
"type":"string",
"value":"logSomething"
"value":"change_color"
}],
"rotation":0,
"type":"",

21
src/event.js Normal file
View File

@ -0,0 +1,21 @@
export default class Event {
constructor(name, action) {
this.name = name
this.action = action
this.triggered = false
this.triggeredThisFrame = false
}
trigger(object) {
this.triggeredThisFrame = true
if (!this.triggered) {
this.triggered = true
this.action(object)
}
}
nextFrame() {
this.triggered = this.triggeredThisFrame
this.triggeredThisFrame = false
}
}

View File

@ -1,5 +1,6 @@
import Player from "./player.js"
import Input from "./input.js"
import Event from "./event.js"
export default class Game {
constructor(canvas) {
@ -12,6 +13,16 @@ export default class Game {
this.input = new Input().initialize()
this.currentRoom = null
this.events = {
"log_test": new Event("log_test", () => console.log("Log events work!")),
"change_color": new Event("change_color", object => object.properties.find(property => property.name == "color").value = "blue")
}
}
triggerEvent(eventName, object) {
const event = this.events[eventName]
if (event) event.trigger(object)
else console.error("Unknown event " + eventName)
}
start() {
@ -31,6 +42,7 @@ export default class Game {
tick(dt) {
this.actors.forEach(actor => actor.tick(dt))
this.currentRoom.tick(this, dt)
Object.values(this.events).forEach(e => e.nextFrame())
}
draw() {

View File

@ -3,7 +3,6 @@ export default class Room {
constructor(json, name) {
this.json = json
this.name = name
console.log(json)
}
tick(game, dt) {
@ -15,7 +14,10 @@ export default class Room {
tickObjectGroup(game, layer) {
const { player } = game
layer.objects.forEach(object => {
if (doRectanglesOverlap(player, object)) console.log(object)
if (doRectanglesOverlap(player, object)) {
const eventName = object.properties.find(property => property.name == "event")?.value
if (eventName) game.triggerEvent(eventName, object)
}
})
}
@ -69,7 +71,7 @@ export default class Room {
drawObjectGroup(ctx, layer) {
layer.objects.forEach(object => {
ctx.fillStyle = "#FF000066"
ctx.fillStyle = object.properties.find(property => property.name == "color").value
ctx.fillRect(object.x, object.y, object.width, object.height)
})
}