diff --git a/rooms/sample.tmj b/rooms/sample.tmj index 622048b..bfc8633 100644 --- a/rooms/sample.tmj +++ b/rooms/sample.tmj @@ -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":"", diff --git a/src/event.js b/src/event.js new file mode 100644 index 0000000..4df60a6 --- /dev/null +++ b/src/event.js @@ -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 + } +} diff --git a/src/game.js b/src/game.js index 458515e..be9ff77 100644 --- a/src/game.js +++ b/src/game.js @@ -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() { diff --git a/src/room.js b/src/room.js index e387d04..54584f2 100644 --- a/src/room.js +++ b/src/room.js @@ -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) }) }