Remembering Between Frames
update() runs fresh every frame — any plain variable you create inside it (let x = 5) gets thrown away and recreated the next frame too. That's fine for things you recalculate every time, but no good for something that needs to stick around, like which direction a shape is currently bouncing.
The fix: store it directly on self, instead of in a local variable. Anything you attach to self stays there, frame after frame, for as long as the game runs.
export function update(self) {
// Only runs the very first frame — after that, self.direction
// already has a value, so this is skipped.
if (self.direction === undefined) {
self.direction = "right";
}
if (self.direction === "right") {
self.setX(self.getX() + 5);
}
if (self.direction === "left") {
self.setX(self.getX() - 5);
}
// Bounce off either edge.
if (self.getX() >= window.innerWidth - 60) {
self.direction = "left";
}
if (self.getX() <= 0) {
self.direction = "right";
}
}
You can name these anything — self.direction, self.health, self.level, self.speed — whatever makes sense for your game. The pattern is always the same: check if it's undefined (meaning "hasn't been set yet"), and if so, give it a starting value.
self that other code can read and change too.