Adding a scrolling camera stuck with the maths

Started by
1 comment, last by CelticSir 9 years, 3 months ago

Hello!

I have an isometric game that I am trying to learn to make. I have my tiles drawn but I am stuck with how I incorporate scrolling with my camera.

My grid to pixel conversion functions are here:


function gridIsoWorld(gridX,gridY,widthHalf,heightHalf) { //isometric grid co-ordinate to a pixel co-ordinate
var x = (gridX - gridY) * widthHalf;
var y = (gridX + gridY) * heightHalf; 
return [x,y];
}


function worldIsoGrid(pixelX,pixelY,widthHalf,heightHalf){ //pixel co-ordinate to an isometric grid co-ordinate
var x = (pixelX / widthHalf  +  pixelY / heightHalf) /2;
var y = (pixelX / heightHalf - (pixelX / widthHalf)) /2;
return [x,y];
}

These work fine, but now I want to also add a camera offset into the mix. My game data holds this information when the game loads:


screen = {};
screen.cameraX  = canvas.width  / 2; 
screen.cameraY  = canvas.height / 2;
screen.gridX  = 2; // tile the camera starts on X axis
screen.gridY  = 2;  // tile the camera starts on Y axis
screen.offsetX  = //need to work this out so tile 2:2 is center of screen
screen.offsetY  = //need to work this out so tile 2:2 is center of screen

When i draw my tiles I use a double for loop which already includes correcting for the camera.offset. Although I have not yet worked out how to calculate the offset which is why my camera is not currently focused on the correct tile.

My draw code:


for(var i = minX; i < maxX; i++){ if(i < 0 || i > max){ continue; }
for(var j = minY; j < maxY; j++){  if(j < 0 || j > max){ continue; }

 var res = gridIsoWorld(i,j,map.grid.widthHalf,map.grid.heightHalf);
 var x   = res[0] - screen.offsetX; //need to calculate this 
 var y   = res[1] - screen.offsetY; //need to calculate this
 
context.drawImage(gridImg,x,y); 

}
}

So yeah I'm kinda stuck how to incorporate the maths for this. Please help, its tricky getting my head around it all some times xD

Advertisement

You can just add or subtract the camera's position

an object is at position


// Screen Coordinates
x = 300;
y = 300;

The camera's top left is at position


x = 200
y = 200

Picturing this in your head you can tell it should render at 100,100 on the screen

soooooo


objX - camX = 100;
objY - camY = 100;

For input....

You clicked the screen at position


x = 100;
y = 200;

Cameras top left position


x = 200;
y = 200;
 
// Coordinates in the world would then be...

x = mouseX + camX; // 300
y = mouseY + camY; // 400
 
gridPos = worldIsoGrid( x,y,widthHalf,heightHalf);

Thanks it works now :)

This topic is closed to new replies.

Advertisement