Skip to content

Instantly share code, notes, and snippets.

@steveruizok
Last active November 16, 2022 18:39
Show Gist options
  • Save steveruizok/3cf65a8545719674dcd48097ada5837e to your computer and use it in GitHub Desktop.
Save steveruizok/3cf65a8545719674dcd48097ada5837e to your computer and use it in GitHub Desktop.
Animate camera
animateCamera = (
x: number,
y: number,
z: number,
opts = {} as { duration: number; ease: (t: number) => number }
) => {
const { duration = 1000 } = opts
const { center } = this.viewport
const currCenter = new Vec2d(center.x, center.y, this.camera.z)
const nextCenter = new Vec2d(x, y, z)
const zoomEase = z < currCenter.x ? EASINGS.easeInCubic : EASINGS.easeOutCubic
const panEase = z >= currCenter.x ? EASINGS.easeInCubic : EASINGS.easeOutCubic
const then = Date.now()
const loop = () => {
const now = Date.now()
const elapsed = now - then
const t = Math.min(1, elapsed / duration)
const zoomT = zoomEase(t)
const panT = panEase(t)
const nx = currCenter.x + (nextCenter.x - currCenter.x) * panT
const ny = currCenter.y + (nextCenter.y - currCenter.y) * panT
const nz = currCenter.z + (nextCenter.z - currCenter.z) * zoomT
const {
viewport: { height, width },
} = this
this.setCamera(-(nx - width / 2), -(ny - height / 2), nz)
if (t < 1) {
requestAnimationFrame(loop)
}
}
requestAnimationFrame(loop)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment