开发者

Camera on HTML 5 Canvas

开发者 https://www.devze.com 2023-03-28 14:22 出处:网络
first time poster here, I have looked for a solution to this for days to no avail, if this has been asked I beg you to link me as I could not find it. Anyways, here goes:

first time poster here,

I have looked for a solution to this for days to no avail, if this has been asked I beg you to link me as I could not find it. Anyways, here goes:

I am working on a tile based canvas app and having issues with moving the camera. Essentially I want to keep the hero in the middle of the screen unless he comes near and edge. I have tried working with using translating the canvas as the hero moves but had issues with shearing. I ended up reworking my logic and now figure out where to start drawing based on the hero's coordinates and then keep my hero drawn at the center of the canvas, it works well until I go near the edges of the screen. Here is my current code for drawing the map, leoX and leoY are the absolute coordinates of the hero, the canvas开发者_开发知识库 is 600X600

var topLeftX = Math.floor((leoX - 300)/33);
var topLeftY = Math.floor((leoY - 300)/33);


//draw map
for(var rowCtr=topLeftY;rowCtr<mapRows;rowCtr++){
for(var colCtr=topLeftX;colCtr<mapCols;colCtr++){

  var tileId = tileMap[rowCtr][colCtr]+ mapIndexOffset;
  var mapSourceX = Math.floor(tileId % 8 )*33;
  var mapSourceY = Math.floor(tileId / 8 )*33;
  context.drawImage(map, mapSourceX, mapSourceY,33,33,(colCtr-topLeftX)*33,(rowCtr-        topLeftY)*33,33,33);

 }
}
//code to draw leo
context.drawImage(tilesheet, sourceX,sourceY,32,48,300,300,32,48);

//update leo's position                 
leoX += leoDeltaX;
leoY += leoDeltaY;

EDIT: Link to example is now dead.

0

精彩评论

暂无评论...
验证码 换一张
取 消