kaplay
kaplay copied to clipboard
feat: make worldPos() and screenPos() accessible
Discussed in https://github.com/marklovers/kaplay/discussions/22
Originally posted by amyspark-ng May 22, 2024 Maybe rework the pos system? Since having 3 different pos may be confusing, maybe not much if the names were changed
I'd like to take a stab at this one too but don't really know how they work, could look into it while also doing the debug.inspect thing
// PosComp methods
// Gives the object's position relative to the root
worldPos(this: GameObj<PosComp>): Vec2 {
return this.toWorld(vec2())
}
// Transforms a point relative to this object to a point relative to the root
toWorld(this: GameObj<PosComp>, p: Vec2): Vec2 {
return this.parent
? this.parent.transform.multVec2(this.pos.add(point))
: this.pos.add(p)
}
// Gives the object's position on the screen
screenPos(this: GameObj<PosComp | FixedComp>): Vec2 {
return this.toScreen(vec2())
}
// Transforms a point relative to this object to a point relative to the screen
toScreen(this: GameObj<PosComp | FixedComp>, p: Vec2): Vec2 {
const pos = this.toWorld(p)
return isFixed(this)
? pos
: toScreen(pos)
}
// Transforms a point relative to the root to a point relative to this object
fromWorld(this: GameObj<PosComp>, p: Vec2): Vec2 {
return this.parent
? this.parent.transform.invert().multVec2(p).sub(this.pos)
: p.sub(this.pos)
}
// Transforms a point relative to this object to a point relative to the other object
toOther(this: GameObj<PosComp>, other: GameObj<PosComp>, p: Vec2) {
return other.fromWorld(this.toWorld())
}
fromOther(this: GameObj<PosComp>, other: GameObj<PosComp>, p: Vec2) {
return other.toOther(this, p)
}
// Global methods
// Transforms a point relative to the screen root to a point relative to the root
fromScreen(p: Vec2): Vec2 {
return game.cam.transform.invert().multVec2(p)
}