Sidescrolling Box2D Game - libgdx

When creating Box2D sidescroller game, is it performance friendly to scroll through every object and move it (for example by x axis) as it does in the following code snap:
for(Body b: bodies) {
b.setTransform(-1, b.getPosition().y, b.getAngle());
}
I was also wondering about the rendering, if I render every texture on every body, I would be rendering the whole level at once and it would cost a lot of my precious FPS.

In contrast to the comments saying that this is a good way to do it, I don't think so.
It is not intuitive to move every entity in your world. When you run around through a forest in real life, the trees also don't move around you, but only you move.
Use an OrthographicCamera and change its position. When rendering via a SpriteBatch, draw all bodies exactly on the position where they are (probably with some METER_TO_PIXEL scaling factor) and use spriteBatch.setProjectionMatrix(camera.combined) on your SpriteBatch. This way only the visible bodies will be drawn automatically, since the camera transformation will get rid of all non-visible bodies.
And another hint: Try to avoid Body.setTransform(). Instead try setting linear velocity or apply forces/torque on the bodies. Using setTransform causes non-physical behaviour since it's basically like teleporting and might lead to weird effects and in my case sometimes even bugs.

Related

Efficient collision detection in AS3

I have a problem with a game that I'm doing. I basically have objects that are in a map and I have to check for each of them if they collide with the walls (and then do something). Since was working with AS2, I thought about doing the same way: I drew a picture with only the walls, so with only rectangles and everything else in between is transparent (does not exist, then the floor for example). In AS2 I put the image to the screen, let's call it wall, and then I did a hitTest to wall with every object. That is for instance, the object was actually on the image, since that the transparent parts were part of it, but the function was testing only on the visible parts, and so with the walls. So it worked.
Now in AS3 there is no HitTest but hitTestObject, which I used, and I do for example wall.hitTestObject(object). The problem is that this function is as if it doens't see the transparencies, and the objects while not touching the walls collide with them!
I found the PixelPerfectCollisionDetection that actually solves the problem but it is huge and heavy so in my case, with so many objects to be tested (at least 60) at each frame, the game slows down a lot!
What I need is a function like hitTestObject (i don't need a lot of accuracy!) that take care of the transparent parts of an image.
How can I do?
As mentioned in the comments, physics/game libraries will have this code built-in for you and should work out of the box.
But if you want to build it yourself, or even introduce your own optimizations, the first step (which is very inexpensive) is checking for bounds collision using entirely built-in functionality of DisplayObject.getBounds and Rectangle.intersects (though you must do so in a consistent coordinate space, i.e. the stage):
if (obj1.getBounds(stage).intersects(obj2.getBounds(stage)) {
// Cheap bounds intersection is true, now do pixel-perfect detection...
}
Then if the bounds check is true, perform the pixel-perfect collision detection.
It seems that BitmapData.hitTest is your best bet - see a blog post by Mike Chambers.
Prior to this method, if you're interested in neat techniques, there was a method outlined by Grant Skinner in his blog. It's quite a clever algorithm using built-in bitmap routines (aka, fairly fast), creating a BitmapData only as large as the overlapping region (or even scaling that down), and drawing the two objects into specific channels of the bitmapdata, then using BitmapData.getColorBoundsRect() to determine if there are any pixels touch. I'm guessing BitmapData.hitTest is faster, but it'd be fun to compare.
I ran into the same problem and to be honest i found the easy way to get rid of that is just generating a "mask" layer for the collisions. You can always place this under your background so it doesn't show, or change the transparencies and whatsoever. Do this in Flash, and after "covering" with rectangles (or whatever) the collisions, just select them all and make that a movie clip.
I'm guessing since you made the symbol in Flash, it obviously knows that even if the symbol consists of several individual drawings or whatever, it's not just an image.
For me this worked fine .

Flashpunk pixel perfect collision on a spritemap

I'm working on a kind of 2d platform ARPG in Flashpunk, and have run into somewhat of a conundrum.
Ranged weapons are no big deal. They are a flat image that I move and rotate to emulate the feel of throwing or firing a ranged weapon. Melee weapons are a bit more of a pain, as I want to use a sprite map for different weapon animations.
The problem I run into is that I have to manually adjust the hitbox for every frame of the melee weapon. I would like to use the Pixelmask function included with Flashpunk, but it does not seem to work with Spritemap. Is there a way to force it to work, or a way to convert the current frame of the Spritemap into an Image so I can apply a Pixelmask?
It's a bit hacky, but what you could do is create a Vector of images separate from the animation itself, with indices equal to that of the corresponding animation, and create the pixelmask from there. If that ends up being too slow (dynamically allocated memory being slower than reusing preallocated), you could load the images, create pixelmasks from them, and push the pixelmasks to a vector instead. From there, all you would need to do is switch to the correct pixelmask during the attack animation.

HTML5 Canvas and Game Programming

I hope this isn't too open ended.
I'm wondering if there is a better (more battery-friendly) way of doing this --
I have a small HTML 5 game, drawn in a canvas (let's say 500x500). I have some objects whose positions I update every 50ms or so. My current implementation re-draws the entire canvas every 50ms. I can't imagine that being very good for battery life on mobile platforms.
Is there a better way to do this? This must be a common pattern with games.
EDIT:
as requested, here are some more updates:
Right now, the objects are geometric primitives drawn via arcs and lines. I'm not opposed to making these small png/jpg/gif files instead of that'd help out. These are small graphics -- just 15x15 or so.
As the game progresses, more and more of the screen changes at a time. However, at the start, the screen changes relatively slowly (the objects randomly moved a few pixels every 50ms).
Nearly every game with continuous animation like this redraws everything every frame; clever updating algorithms are only applicable when a small part of the screen is changing and there is a nice rule to figure out what is overlapping that part.
Here is some general optimization advice:
Make sure that as much as possible of your graphics are handled by the GPU and not the CPU. (This may be impossible if the user's browser does not use the GPU for 2D canvas rendering, but you can expect upgrades may change that as HTML5 gaming gains popularity.)
This means that you should avoid elaborate clever algorithms in favor of doing as little work as possible in JS code — except that avoiding performing a lot of drawing when it is easy to determine that it will be invisible (e.g. outside the bounds of the screen) is generally worthwhile.
If your target platforms support it (generally not the case for current mobile devices), try using WebGL instead of 2D Canvas. You will have to do more detail work, but WebGL allows you to use operations which are much more likely to be provided efficiently by the GPU hardware.
If your game becomes idle — that is, nothing is actually animating at the moment — stop redrawing. Stop your update loop until the user interacts with the game or a timeout occurs.
It may be helpful for you to add to your question details of what types of graphics you are drawing (e.g. are you using sprites, or geometric primitives? Are you drawing images rotated/scaled? Does most of the screen change or just a few small objects? Are you blending many layers?) and perhaps even a screenshot or two; then we can suggest what sort of optimizations are suitable for your particular game.
Don't draw a background, make it an image and set the CSS background-image of the canvas.
Using requestAnimationFrame should help with battery life.
http://paulirish.com/2011/requestanimationframe-for-smart-animating/
Only do a redraw if something has actually changed. If you haven't already, introduce the concept of invalidations. (ie, the canvas is valid so nothing redraws until something moves. Anything moving within the window of the canvas causes the canvas to become invalid, thus needing a redraw)
If you want to be battery friendly you can use Crafty. This game engine is using modern CSS3 technology so it doesn't need to update a canvas all the time. Look at this example game here.
The way you don't want to redraw entire canvas every frame, it only can be the "Dirty-Check" or "Dirty Matrix" algorithms.
Dirty-check seems more efficient than entire redraw. but I think it depends on your render implementation.
it is not necessary to use it if you are using canvas2D to render. Nearly every game has complex sprites and animation. if you use dirty-check, when a part of sprite or background map need to update, you have to figure out what is overlapping this part. and then clearRect this small area of canvas, and then redraw every sprite or map. etc, what is overlapping.
It means your had to run canvas render api more times than normal render implementation because of the overlapping part. And Canvas2d render performance usually does't sounds efficient.
But if you use WebGL, that maybe quite difference. even though I am not family with WebGL, I do knew that maybe more efficient. Dirty-Check should be a good Choice to match your propose.

Will avoid drawing half pixel in HTML5 canvas improve speed?

I am drawing a sprite (of a ball) on a canvas element. As the ball moves however, the x or y position of the ball may become a fraction, eg. (20.153; 63.638). When canvas is used to draw this image, it attempts to use transparent pixels to make the ball appear in it's position more accurately.
I was wondering whether I should use Math.round() before drawing the ball to avoid the transparent pixel stuff, and possibly speeding up the game a lot. Will this help much? The game is a sorta complex pong game.
The image below should help with my explanation:
At least this guy seems to believe so. As Gabe mentioned, it depends on the implementation.
Note that some sort anti-aliasing seems to kick in if you are using regular coords (1, 14, etc.). For this reason some guides (Dive Into HTML5 mainly) seem to suggest that you are better off by rending using half pixels (ie. 1.5, 14.5, etc.). I don't know if this makes any difference to performance, though. It's noticeable on render result at least.
You might also want to experiment with various layering schemes. See this question for more information. Depending on your situation you might want to treat your objects as separate canvases even and just offset them on top of the background.
Alternatively you could try to render it all on one canvas. In this case you have some extra stuff to keep track of. This library seems to handle all the bookkeeping for you.

Howto dynamically render space background in actionscript3?

I'm creating a space game in actionscript/flex 3 (flash). The world is infinitely big, because there are no maps. For this to work I need to dynamically (programatically) render the background, which has to look like open space.
To make the world feel real and to make certain places look different than others, I must be able to add filters such as colour differences and maybe even a misty kind of transformation - these would then be randomly added and changed.
The player is able to "scroll" the "map" by flying to the sides of the screen, so that a certain part of the world is only visible at once but the player is able to go anywhere. The scrolling works by moving all objects except for the player in the opposite direction, making it look like it was the player that moved into that direction. The background also needs to be moved, but has to be different on the new discovered terrain (dynamically created).
Now my question is how I would do something like this, what kind of things do I need to use and how do I implement them? Performance also needs to be taken into account, as many more objects will be in the game.
You should only have views for objects that are within the visible area. You might want to use a quad tree for that.
The background should maybe be composed of a set of tiles, that you can repeat more or less randomly (do you really need a background, actually? wouldn't having some particles be enough?). Use the same technique here you use for the objects.
So in the end, you wind up having a model for objects and tiles or particles (that you would generate in the beginning). This way, you will only add a few floats (you can achieve additional performance, if you do not calculate positions of objects, that are FAR away. The quad tree should help you with that, but I think this shouldn't be necessary) If an object having a view leaves the stage, free the view, and use the quad tree to check, if new objects appear.
If you use a lot of objects/particles, consider using an object pool. If objects only move, and are not rotated/scaled, consider using DisplayObject::cacheAsBitmap.