Getting Another Shape
So far, every example has a shape only reading or changing itself. Sometimes you want one shape's code to affect a different shape — a spiky hazard that damages the player, a switch that changes another shape's color, a coin that adds to someone else's score.
Game.getShape(otherId) hands you a reference to another shape — the exact same self its own code gets — so you can read or change its position, color, or anything stored on it:
export function update(self) {
if (self.isTouchingOnce("player")) {
const player = Game.getShape("player");
if (player) {
player.health -= 10;
}
}
}
A few important things about that example:
- Always check the result isn't empty first.
Game.getShape(...)gives back nothing if that id doesn't exist (a typo, or it's been deleted) — always checkif (player)before using it, or your code will crash trying to use something that isn't there. - The other shape's value has to already exist. If
player.jsnever setsself.healthanywhere,player.healthis empty (undefined), andundefined - 10gives youNaN(not a real number) — not a crash, but a bug that's hard to spot. Make sure the shape you're reading from sets its own starting value first, the same way shown in "Remembering Things Between Frames."
This is what makes it possible to split game logic across shapes — one shape's file can hold a value like health, while a completely different shape's file changes it. Neither file needs to know how the other one works internally, just the name of the value.
Game.getShape(...) works from any shape's code without any setup — just like Game.restart().