mmag

ハマったことメモなど

KAPLAYでカメラをキャラクターに追従させる

基本は

k.camPost(target.worldPos())

なんだけど、常に追いかけるんじゃなくて画面の真ん中あたりでは追従しないでほしい。

function follow(target: GameObj<PosComp>) {
  let { x: nextX, y: nextY } = k.camPos()
  const { x: sX, y: sY } = target.screenPos()
  const { x: wX, y: wY } = target.worldPos()
  const width = k.width()
  const height = k.height()
  const marginX = 0.3 * width
  const marginY = 0.3 * height

  if (sX < marginX) {
    nextX = wX - marginX + 0.5 * width
  } else if (width - marginX < sX) {
    nextX = wX + marginX - 0.5 * width
  }

  if (sY < marginY) {
    nextY = wY - marginY + 0.5 * height
  } else if (height - marginY < sY) {
    nextY = wY + marginY - 0.5 * height
  }

  nextX = Math.min(Math.max(nextX, width / 2), levelWidth - width / 2)
  nextY = Math.min(Math.max(nextY, height / 2), levelHeight - height / 2)

  k.camPos(k.vec2(nextX, nextY))
}

levelWidthは世界の幅。minとかmaxとかやってるのは世界の外側を映さないように制限しているだけ。

無難にGodotにしておけばいいのに。