Flashpunk pixel perfect collision on a spritemap - actionscript-3

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.

Related

Sidescrolling Box2D Game

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.

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 .

Animation optimization for many identical vector shapes in AS3/AIR

I have many small, identical vector circles that move around the screen, but only appear for a defined period in defined areas. Currently, these circles are children of whatever parent object produces them, and each is given its own interframe handler for animation (move a few pixels, maybe change alpha). With hundreds on screen, this gets somewhat slow.
Would it be advisable to cache the circles as bitmaps? Would it be better to add them all to one array and have one interframe event handler run through the whole shebang, even if up to 90% aren't being animated in a specific frame?
Would it be faster to cache one circle as a bitmap and set all others to use the first shape's bitmapdata? Would it be even better to use a "CopyPixel" approach to erase and redraw ("blit") every circle at its new position every frame? I hear conflicting reports of the usefulness of CopyPixel on large mobile device canvases...
If the animation can be looped make a movie from the movie else try everything you can. Usually a CopyPixel approach is faster but I wouldn't expect much. I don't think it pays the bill either hence reduce the numbers of circles.

Each frame calculation vs pre-rendered bitmaps

We create some MovieClips and use Motion Tween to animate them.
We create some MovieClips and use Motion Tween to animate them, then render all frames as .png and create MovieClips with all those rendered .pngs.
I guess second way take less time, because you skip tween calculation step. Which way of animation is more proper/fast?
It's of course the first one. Maybe your intention is good but it wouldn't pay off in the long term and it's also micro-optimization and it's considered bad. It doesn't make the code readable and it can slow down your loading time. In general calculation is also faster because you don't need to change the whole screen. So it really depends if the second version uses for example delta packing for the 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.