HTML and CSS Reference
In-Depth Information
Camera
To render a world, you need a camera , which contains the transformation information from display coordinates to
world coordinates. Coordinates describe a transform on a map ( centerX , centerY ) that corresponds to the center of
the screen and a scale. The clientRect function constructs a rectangle on the map that corresponds to the display
rectangle: ( rect.x , rect.y ) to (0, 0), ( rect.x + rect.w , rect.y + rect.h ) to ( displayWidth , displayHeight ). The following code
implements the camera and clientRect functions:
function Rect(x, y, w, h) {
this.x = x
this.y = y
this.w = w
this.h = h
}
Rect.prototype = {
contains: function(x, y) {
return this.x <= x && x < this.x + this.w && this.y <= y && y < this.y + this.h
}
}
var Camera = function(map, canvas) {
this.canvas = canvas; this.map = map
this.centerX = this.mapWidth() >> 1
this.centerY = this.mapHeight()>> 1
}
Camera.prototype = {
mapWidth: function() { return this.map.cols * TILE_SIZE },
mapHeight: function() { return this.map.rows * TILE_SIZE },
displayWidth: function() { return this.canvas.width },
displayHeight: function() { return this.canvas.height },
context: function() { return this.canvas.getContext("2d") },
centerX: 0,
centerY: 0,
scale: 1,
map: null,
canvas: null,
clientRect: function() {
var dw = this.displayWidth(), dh = this.displayHeight();
var dw2 = dw >> 1, dh2 = dh >> 1
// (0, 0) in display corresponds to (rect.x, rect.y)
// (displayWidth, displayHeight) to (rect.x+rect.w, rect.y+r.h)
return new Rect(this.centerX - dw2*this.scale, this.centerY - dh2*this.scale,
dw*this.scale, dh*this.scale);
},
moveBy: function(dx, dy) {
//move center by display coordinates
this.centerX = Math.min(Math.max(this.centerX - dx * this.scale, 0), this.mapWidth());
this.centerY = Math.min(Math.max(this.centerY - dy * this.scale, 0), this.mapHeight());
},
 
Search WWH ::




Custom Search