kaplay icon indicating copy to clipboard operation
kaplay copied to clipboard

feat: make worldPos() and screenPos() accessible

Open amyspark-ng opened this issue 1 year ago • 2 comments

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

amyspark-ng avatar May 23 '24 00:05 amyspark-ng

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

amyspark-ng avatar May 23 '24 00:05 amyspark-ng

// 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)
}

mflerackers avatar May 23 '24 07:05 mflerackers