I have a javascript game where I use a tile grid somewhat like this:

var tiles = [
[0, 0, 0],
[0, 1, 0],
[0, 0, 1]

I want a camera to follow the player and when the player moves off the map, shift the camera over to new tiles. Even better just a map that follows the player.

  • \$\begingroup\$ You should describe your camera interface. Is it some object that's easly movable? \$\endgroup\$ – Marqin Jan 9 '16 at 23:28
  • \$\begingroup\$ Are you using DOM or a canvas to render your grid? \$\endgroup\$ – Philipp Apr 9 '16 at 11:20

In general, when you want to follow player, the way to do this is to update camera's position after every player position update:

for( var i = 0; i < DIMENSIONS; i++ ) {
    camera.position[i] = player.position[i] + camera.offset[i];

Offset should be set in your game editor or in game init, as the difference between player and camera initial positions ( which were set up in game editor ):

for( var i = 0; i < DIMENSIONS; i++ ) {
    camera.offset[i] = camera.position[i] - player.position[i];

Add map and objects to a container.

Example: container.x = -camera.x (illusion camera moved through world)

a = OBJECT location

b = TARGET location

t = decimal between 0 and 1

function lerp(a, b, t)
  return a + (b - a) * t

Return INTEGER to move from a to b. As a is closer to b, integer will become smaller (deceleration).

camera.x = 100

target.x = 200

spring = 0.6

integer = lerp(camera.x,target.x,spring)
camera.x += integer
container.x = -camera.x

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.