Sunday, August 9, 2015

javascript - Optimizing isometric drawing function


I need help optimizing my Draw(); function to draw only what is visible in the viewport. Currently I'm drawing the whole Map array in a diamond shape. How can I make my function store only what is visible?


Here is an image explaining it better: enter image description here Black tiles are X axis, White tiles Y axis. Green tiles are what I would like the function to store, and the Orange rectangle is the viewport.


I'll include the relevant part of my code aswell:


for(i=0;i
for (j=0;jtileX = (i - j) * (tile.width / 2);
tileX += (canvas.width /* 2*/) - (tile.width / 2);
tileY = (i + j) * (tile.height / 2);
tileY -= (canvas.height /* 2*/);

c.drawImage(tile, tileX, tileY);
}
}


I've been trying to figure out how to solve this, but since I'm no genius I can't. Help appreciated.



Answer



(migrated from comments) This is kind of a duplicate of a previous answer I gave to How do I find which isometric tiles are inside the camera's current View.


The way I handle this is by iterating over horizontal/vertical rows and columns. I'll call these axes A/B instead of X/Y (which you're already using for the diagonal axes in your isometric view).


Translating X,Y to A,B is as simple as A = X+Y, B = X-Y. The reverse transformation is X = (A+B)/2, Y = (A-B)/2. If you choose a rectangle such that min, and min', then it corresponds to a particular rectangular viewpoint.


Here is the jsfiddle: http://jsfiddle.net/kAFVB/3/


Here are a couple examples of how different choices of A and B change the dimensions of the viewable area (the shaded rectangle is the same rectangle in both pictures)


enter image description here


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...