Search code examples
javascriptcanvasdictionary2dtile

javascript 2d tile based game rendering (terraria-style)


I have made terraria clones in the past. They're quite fun as a project, I find. But with the 1.2 update of Terraria, I want a clone that I can run on any computer anywhere anytime. So I'm working with HTML5.

At first, I thought it would be simple - as it has been in the past with the other languages I've used.

But once I got into it, I started facing many problems. I do NOT have any code to share, because I've deleted it all and tried again countless times. I can only do edits on my website live, so when I want to try again, I either make a new page entirely, or just edit the page I currently have. For lack of unlimited storage, I edit the page I currently have.

Some pseudo code for what I have tried is this:

Set the fillStyle to black. Loop through the width and height/16 and create x amount of rect()'s. Fill all the rects. Draw the player (either with an image or another rect in a different colour).

Which works fine, I can render it all just great. But it takes a lot longer than I would like. I'd be getting about .4FPS if I used this for rendering. So what I'm wondering, is how can I go about rendering a 2d tile based map that extends past the area of the viewport efficiently?

I don't want theories, I know the concepts. I need help understanding how to IMPLEMENT the concepts. Some code that does this quasi efficiently would be fantastic to see.

EDIT:

I can only do edits live because I use a chromebook. There is no option for me to use a text editor and then upload the files when they're completed.


Solution

  • If you rendered the whole thing once then you would get less lag. Maybe have 16x16 grids within the whole map that can be saved and then rendered as a whole as needed? You could (re)render them when they are modified and when they first appear.