Should I use ctx.translate for an endless game-map? - javascript

Well, just imagine you keep going up but your player stays put in the middle, and as you go up the map generates itself randomly.
With the help of:
ctx.translate(0, 1);
the map moves towards you as you move up.
now, I have a few methods in mind and of them is ctx.translate, but I have a few questions:
1) in the long run, what I fear is that it will keep the memory of the previous drawings once they go out of the canvas borders and eventually the ctx x/y system will go to numbers as high as millions.
2)I need something which is CPU friendly. I am just not sure what ctx.translate does under the hood exactly, does it behave in the likes of ctx.clearRect and then redraws everything?
3) anything better to achieve the same thing will be lovely, I already know about the old clearRect(which is heavy) and redraw method, just looking for other options.
EDIT: the player may change his X coordinate in some position too.

Related

Detect mouse collision on a 2d grid without using loops

I am building a maze solver and recently I wanted to be able to draw over the grid without having to manually build mazes using arrays. Anyway, I sat down and thought "there has to be a more efficient way to figure out which cell the mouse has collided with on click event, instead of having to iterate over the whole grid which at worst case scenario costs O(n^2)."
After some thinking I came up with the following solution.
I knew that the size of each grid was constant (in my case 16x16) and I knew the position of the mouse. So I decided to divide mouse position by tileSize and then round it down.
My question is if this is a better solution than iterating over the whole grid, cell by cell. I haven't seen anyone do it this way so I am wondering if there's some edge case that I haven't thought of which might not work with this solution.
What you did is the standard way to do it. It never occurred to me to do it via looping of any kind honestly.
Since this is tagged javascript I'm gonna go ahead and recommend this answer of mine in case you have any problems getting the right coordinates for a canvas that was stretched or has borders: https://stackoverflow.com/a/27204937/607407
The linked answer determines pixel the mouse is over exactly using the formula in your question, with tileSize being one. For given tileSize, the tile is then [floor(x/tileSize), floor(y/tileSize)].

How multiple canvas elements affect performance?

I'm trying to make a simple game (view from above) on canvas. Please tell me, which is faster:
1) Draw everything on one <canvas> and calculate the areas that need to be redrawn.
2) Draw certain parts of the scene on different <canvas> elements and update each only if necessary. In the it variant, probably, I can also use a partial redraw.
For example, I could draw a map on one element, enemies on the second, and a cursor and etc on the third. When moving enemies, I could only redraw the second canvas.
Please explain in as much detail as possible which option is better and why. And could you please advise books that can deepen my knowledge on this issue? For beginners.
Most canvas games will use a sort of layering that you are describing. The furthest forward layer would be the HUD, either by a seperate canvas or HTML elements and this would only change if something happened to it, such as someone upgrading their player. Then after that it depends on how they draw the canvas. The simplest way would be to simply draw the portions of the map and obstacles are on the screen.
Use one canvas, trust me. If you have a sprite that does nothing but sit there it is still getting drawn 60 times a second so it makes no difference if it is moving or not changing or not if it exists on screen it is getting drawn regardless of change.

JavaScript canvas game development

Ive been having a really baffling slow down issue with the game I am working on probably because I am unsure how to handle graphics (most likely responsible for the slow down) in javascript without using a third party framework like Phaser/ImapactJS/EaselJS etc)*. The following is the low down on how I am approaching my graphics. I would be very thankful for some tips or methods on how to do this right.
My game is tile based - using tiles designed at 500x500 px because I want them to display decently on high definition devices.
I am using a spritesheet to load all (most of) my tiles before the main loop is run. This image is roughly 4000 x 4000 (keeping it below 4096 because the GPU cant handle texture sizes larger than that).
I then use the drawImage function to cycle through and draw each tile on a part of the canvas using information (w, h, x, y) stored in the tile array. I do this on every cycle of the main loop using my drawMap function.
The map is currently 6x6 tiles in size
A character spritesheet is also loaded and drawn on to the canvas after the map has been drawn. The character displays a different frame of the animation on every cycle of the main loop. There are sets of animations for the character each contained in the same spritesheet.
The character sprite sheet is roughly 4000x3500
The character is roughly 350x250 px
Other objects also use the same sprite sheet. Currently there is only one object.
Possibly helpful questions:
Am I using too many spritesheets or too few?
Should I only draw something if it's coordinates are in bounds of the screen?
How should I go about garbage collection? Do I need to set image objects to null when no longer in use?
Thanks in advance for input. I would just like to know if I am going about it the right way and pick your brains as how to speed it up enough.
*Note that I plan to port the JS game to cocoonJS which provides graphics acceleration for the canvas element on mobile.
** If interested please visit my Patreon page for fun!
You have asked lots of questions here, I'll address the ones I've run into.
I would like to start out by saying very clearly,
Use a profiler
Find out whether each thing you are advised to do, by anybody, is making an improvement. Unless we work on your code, we can only give you theories on how to optimise it.
How should I go about garbage collection? Do I need to set image objects to null when no longer in use?
If you are no longer using an object, setting its reference to null will probably mean it gets garbage collected. Having nulls around is not necessarily good but this is not within the scope of this question.
For high performance applications, you want to avoid too much allocation and therefore too much garbage collection activity. See what your profiler says - the chrome profiler can tell you how much CPU time the garbage collector is taking up. You might be OK at the moment.
I then use the drawImage function to cycle through and draw each tile on a part of the canvas using information (w, h, x, y) stored in the tile array. I do this on every cycle of the main loop using my drawMap function.
This is quite slow - instead consider drawing the current on screen tiles to a background canvas, and then only drawing areas which were previously obscured.
For example, if your player walks to the left, there is going to be a lot of tiles on the left hand side of the screen which have come into view; you will need to draw the background buffer onto the screen, offset to account for the movement, and then draw the missing tiles.
My game is tile based - using tiles designed at 500x500 px because I want them to display decently on high definition devices
If I interpret this right, your tiles are 500x500px in diameter, and you are drawing a small number of these on screen. and then for devices without such a high resolution, the canvas renderer is going to be scaling these down. You really want to be drawing pixels 1:1 on each device.
Would you be able, instead, to have a larger number of smaller tiles on screen - thereby avoiding the extra drawing at the edges? Its likely that the tiles around the edges will sometimes draw only a few pixels of one edge, and the rest of the image will be cropped anyway, so why not break them up further?
Should I only draw something if it's coordinates are in bounds of the screen?
Yes, this is a very common and good optimisation to take. You'll find it makes a big difference.
Am I using too many spritesheets or too few?
I have found that when I have a small number of sprite sheets, the big performance hit is when I frequently switch between them. If during one draw phase, you draw all your characters from character_sheet.png and then draw all the plants from plant_sheet.png you'll be ok. Switching between them can cause lots of trouble and you'll see a slow down. You will know this is happening if your profiler tells you that drawImage is taking a big proportion of your frame.

Canvas vs DOM Element game and collision

So I am trying to make a little game both for practice and fun (first time I have tried) never had anything to do with it before..
You can see what I've tried so far at: http://myfirstgame.e-ddl.com/ been working on it for like 6-8 hours or so. So far and realized I would better ask before going on.
The way I have it now, I have a main loop that runs every 20 milliseconds or so. Ihis loop calls 2 functions:
Handle keystrokes (which iterates through the obstacles array and check if the player's future position collide any obstacle object and change the players' properties to the future position values).
It goes through the "need update" array and change the element's CSS details to reflect the changes made.
I have several questions:
Is the above a good idea to handle collision? if not what would be a better way (I mean at around 800-1500 obstacle objects on map the game slows down).
To calculate distance, I use distance between 2 points equation. If I only have 1 point, angle and distance. How can I find the 2nd point's (x, y)?
What would be better, canvas or DOM ? (not important question as I already have it done with DOM).
Thanks for everyone.
I've found the solution to what i were looking for.
about the collision the way i was doing it was entirely wrong i will list the correct way farther down.
about the distance - the solution i came up with is checking the distance from player's current position to object if player's step is bigger then distance, deduct step from distance and walk that distance.
as for canvas vs dom - seems both has their crons and pros.
Now for the collision
the correct way of doing it is to create a pixel map array. so if your canvas or container node is width:800 by height:500 you'll have a 2d array that represent those pixes
and then when i check for position i simply check if player's current position + steps toward future position has an object.
so like :
if(array[300][500]){
return false;
}
That's what i found out.
If anyone have a better solution then that let me know.

Position resizable circles near each other

I am working on this browser-based experiment where i am given N specific circles (let's say they have a unique picture in them) and need to position them together, leaving as little space between them as possible. It doesn't have to be arranged in a circle, but they should be "clustered" together.
The circle sizes are customizable and a user will be able to change the sizes by dragging a javascript slider, changing some circles' sizes (for example, in 10% of the slider the circle 4 will have radius of 20px, circle 2 10px, circle 5 stays the same, etc...). As you may have already guessed, i will try to "transition" the resizing-repositioning smoothly when the slider is being moved.
The approach i have tried tried so far: instead of manually trying to position them i've tried to use a physics engine-
The idea:
place some kind of gravitational pull in the center of the screen
use a physics engine to take care of the balls collision
during the "drag the time" slider event i would just set different
ball sizes and let the engine take care of the rest
For this task i have used "box2Dweb". i placed a gravitational pull to the center of the screen, however, it took a really long time until the balls were placed in the center and they floated around. Then i put a small static piece of ball in the center so they would hit it and then stop. It looked like this:
The results were a bit better, but the circles still moved for some time before they went static. Even after playing around with variables like the ball friction and different gravitational pulls, the whole thing just floated around and felt very "wobbly", while i wanted the balls move only when i drag the time slider (when they change sizes). Plus, box2d doesn't allow to change the sizes of the objects and i would have to hack my way for a workaround.
So, the box2d approach made me realize that maybe to leave a physics engine to handle this isn't the best solution for the problem. Or maybe i have to include some other force i haven't thought of. I have found this similar question to mine on StackOverflow. However, the very important difference is that it just generates some n unspecific circles "at once" and doesn't allow for additional specific ball size and position manipulation.
I am really stuck now, does anyone have any ideas how to approach this problem?
update: it's been almost a year now and i totally forgot about this thread. what i did in the end is to stick to the physics model and reset forces/stop in almost idle conditions. the result can be seen here http://stateofwealth.net/
the triangles you see are inside those circles. the remaining lines are connected via "delaunay triangulation algorithm"
I recall seeing a d3.js demo that is very similar to what you're describing. It's written by Mike Bostock himself: http://bl.ocks.org/mbostock/1747543
It uses quadtrees for fast collision detection and uses a force based graph, which are both d3.js utilities.
In the tick function, you should be able to add a .attr("r", function(d) { return d.radius; }) which will update the radius each tick for when you change the nodes data. Just for starters you can set it to return random and the circles should jitter around like crazy.
(Not a comment because it wouldn't fit)
I'm impressed that you've brought in Box2D to help with the heavy-lifting, but it's true that unfortunately it is probably not well-suited to your requirements, as Box2D is at its best when you are after simulating rigid objects and their collision dynamics.
I think if you really consider what it is that you need, it isn't quite so much a rigid body dynamics problem at all. You actually want none of the complexity of box2d as all of your geometry consists of spheres (which I assure you are vastly simpler to model than arbitrary convex polygons, which is what IMO Box2D's complexity arises from), and like you mention, Box2D's inability to smoothly change the geometric parameters isn't helping as it will bog down the browser with unnecessary geometry allocations and deallocations and fail to apply any sort of smooth animation.
What you are probably looking for is an algorithm or method to evolve the positions of a set of coordinates (each with a radius that is also potentially changing) so that they stay separated by their radii and also minimize their distance to the center position. If this has to be smooth, you can't just apply the minimal solution every time, as you may get "warping" as the optimal configuration might shift dramatically at particular points along your slider's movement. Suffice it to say there is a lot of tweaking for you to do, but not really anything scarier than what one must contend with inside of Box2D.
How important is it that your circles do not overlap? I think you should just do a simple iterative "solver" that first tries to bring the circles toward their target (center of screen?), and then tries to separate them based on radii.
I believe if you try to come up with a simplified mathematical model for the motion that you want, it will be better than trying to get Box2D to do it. Box2D is magical, but it's only good at what it's good at.
At least for me, seems like the easiest solution is to first set up the circles in a cluster. So first set the largest circle in the center, put the second circle next to the first one. For the third one you can just put it next to the first circle, and then move it along the edge until it hits the second circle.
All the other circles can follow the same method: place it next to an arbitrary circle, and move it along the edge until it is touching, but not intersecting, another circle. Note that this won't make it the most efficient clustering, but it works. After that, when you expand, say, circle 1, you'd move all the adjacent circles outward, and shift them around to re-cluster.

Categories

Resources