puzzle/game/Camera.js

85 lines
1.9 KiB
JavaScript
Raw Normal View History

2020-11-07 11:35:29 +01:00
export default class Camera {
constructor(canvas) {
this.x = 0
this.y = 0
2020-11-07 17:49:42 +01:00
// TODO: when canvas resizes, this should
2020-11-07 11:35:29 +01:00
// syncronize with the cam
this.width = canvas.width
this.height = canvas.height
this.zoom = 1
this.minZoom = .2
this.maxZoom = 6
this.zoomStep = .05
}
rect() {
2020-11-10 18:48:16 +01:00
return {
x: -this.x,
y: -this.y,
w: this.width / this.zoom,
h: this.height / this.zoom,
}
2020-11-07 11:35:29 +01:00
}
2020-11-07 17:49:42 +01:00
2020-11-07 11:35:29 +01:00
move(x, y) {
this.x += x / this.zoom
this.y += y / this.zoom
}
2020-11-12 19:19:02 +01:00
setZoom(newzoom) {
const zoom = Math.min(Math.max(newzoom, this.minZoom), this.maxZoom)
if (zoom == this.zoom) {
2020-11-07 11:35:29 +01:00
return false
2020-11-12 19:19:02 +01:00
}
// centered zoom
2020-11-17 21:46:56 +01:00
// TODO: mouse-centered-zoom
2020-11-12 19:19:02 +01:00
this.x -= Math.round(((this.width / this.zoom) - (this.width / zoom)) / 2)
this.y -= Math.round(((this.height / this.zoom) - (this.height / zoom)) / 2)
this.zoom = zoom
return true
2020-11-07 11:35:29 +01:00
}
2020-11-12 19:19:02 +01:00
zoomOut() {
return this.setZoom(this.zoom - this.zoomStep)
}
2020-11-07 11:35:29 +01:00
2020-11-12 19:19:02 +01:00
zoomIn() {
return this.setZoom(this.zoom + this.zoomStep)
2020-11-07 11:35:29 +01:00
}
2020-11-08 23:42:36 +01:00
/**
* Translate a coordinate in the viewport to a
* coordinate in the world
* @param {x, y} coord
*/
viewportToWorld(coord) {
2020-11-07 11:35:29 +01:00
return {
2020-11-12 19:19:02 +01:00
x: Math.round((coord.x / this.zoom) - this.x),
y: Math.round((coord.y / this.zoom) - this.y),
2020-11-07 11:35:29 +01:00
}
}
2020-11-07 17:49:42 +01:00
2020-11-08 23:42:36 +01:00
/**
* Translate a coordinate in the world to a
* coordinate in the viewport
* @param {x, y} coord
*/
worldToViewport(coord) {
2020-11-07 17:49:42 +01:00
return {
2020-11-12 19:19:02 +01:00
x: Math.round((coord.x + this.x) * this.zoom),
y: Math.round((coord.y + this.y) * this.zoom),
2020-11-07 17:49:42 +01:00
}
}
2020-11-10 18:48:16 +01:00
worldDimToViewport(dim) {
return {
2020-11-12 19:19:02 +01:00
w: Math.round(dim.w * this.zoom),
h: Math.round(dim.h * this.zoom),
2020-11-10 18:48:16 +01:00
}
}
2020-11-07 17:49:42 +01:00
}