AS3 obstacles hitTest - actionscript-3

Okay, I have read some articles about basic platformer creation, people say it's the hardest part - to make correct collisions at high speeds. Indeed, even if I have 60 fps, an object moving at like 50-100 pixels per tick is hard to trace. The problem is, if it hits a wall, it passes through it, detects going too far and returns the object to a defined point next to a wall with speed 0 (or ricochets). But if I have a 5 pixel wall in a middle of a stage, even at low speeds collision may just be missed. Yeah, you'd say "make 2 areas, check if object in one, another will be a whole hitTest zone to return from it" but what if I need a maze of randomly drawn walls? What is a good way to make thin walls an object wouldn't pass?
Thinking of platformer, I recall Castlevania and Metroid, it wasn't AS3, but still, maybe you know how they did it so smooth? Good fps? Predicting collisions? Or does nobody make crazy speeds like a ricocheting bullet?
I could really use some ideas before I dive into coding. I wish to at least know I'm moving the right way, even if it's hard. To not end up with 1000 lines, not remembering where is what and CPU load # 95% for 1 single object XD My guess for now is make 4 invisible blocks right, left, up and down of the object and count each side collisions separately. But it may get ugly on the corners. 8 blocks maybe?

At the moment, you're checking if the object is intersecting with a wall at the exact moment the frame happens, but really you want to know if the object ever intersected with the wall between the last frame and now. You can imagine a line between where the object was before and where it is now, so essentially you need to check if that line intersects with the line of the wall.
It's quite old, but tonypa has a nice tutorial here which goes over all of the basics.

Related

Bullet - Rigid bodies not colliding at high speed?

I'm trying to make a basic first person shooter game with Bullet and OpenGL. I'm having the issue of my rigid bodies not colliding at high speed.
My bullets will go straight through any other rigid bodies that I have, such as walls. Reducing velocity to less than 10 does result in collisions, but this is too low for a moving bullet. The bullet also moves insanely fast (I know it's a fast moving bullet, but sometimes I can't even see it, not sure if that's expected).
I'm thinking that it's to do with how I'm stepping the simulation? Reading up on it has left me confused. How can I make it so that my objects will always collide (at least, when going reasonably fast), and if possible, is there a way to slow the simulation down whilst maintaining the correct bullet velocity etc. so that I can actually see the bullet moving and colliding?
Here are some approaches to solve:-
It is copied from How can I avoid missing collisions for fast moving objects? - an official FAQ
smaller timesteps
extruding the object along the motion
ray cast to the new position
swept collision test (convex cast, linear cast)
continuous collision detection, including rotational motion
Please read the link for more detail. It is not a trivial issue.
One important thing to ask before try anything: do you really need high speed object?
It is not free (cost more CPU).
Here is another useful link (less useful though) : https://gamedev.stackexchange.com/questions/11961/how-can-i-enable-ccd-in-bullet-physics

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 .

AS3 with Nape physics: How can I find a tangent from a point to a body?

The short question: Is there any simple way in Nape to calculate the points of tangency with a Nape body object or shape given a point outside that body?
What I'm trying to do is create Worms-style rope physics. It basically works as an extendable line/distance joint that automatically breaks into segments when it comes in contact with the level geometry. I do this by raycasting from the most recent pivot point; if there is a collision I offset from the collision point by a couple of pixels, create a new rope segment, and make that point the new pivot. In case my character is swinging around a sharp corner, I then recast from that point, looping as necessary, until I'm clear of the level geometry.
It works amazingly well given my lack of experience, but there's one little cosmetic glitch. The rope won't wrap "tightly" around a horn-shaped protrusion. It's pretty easy to see why this is happening. Refer to the figure below.
I cast a ray each time I step the Nape world at 60 frames/second. Figure 1 shows the difference between two example raycasts. The character (not pictured) is at the end of the line, and he's fallen past the cliff "edge" in relation to the pivot in one step, so the collision point falls short of the desired point of tangency.
Figure 2 is what I end up with. The wraparound logic still works, by offsetting from the surface and recasting, but it doesn't appear "taut."
What I want is something like Figure 3, which corrects the angle to find the actual point of tangency with the body and creates the new pivot from that.
My planned fallback is to offset the angle of the raycast by small increments and recast until I no longer strike the level geometry, then back up one and use that as the collision point. Even that will probably require fewer computations than "curving" around like in Figure 2, but I'm still wondering: is there an even simpler way?
Excuse me for not commenting, but I don't have needed points for that :)
I've used something similar before (not exactly the same) and I think the way to go is to save the points of each cast, get the one with highest difference from the starting point, based on the y axis (if the rope goes up, then you get the point with smallest y and vice versa (rope going down from starting point)).
Then you can fix the angle to point to this specific point, marked as an "edge". Later you can continue with the common pattern, as the rope will go in the other direction (exactly like the edge of a cliff).

Collision and bounce detection from array of points

I have an array of points that I will use to generate a closed polygonal fence on the outside of a game stage (2D). I wish to have collision detection between this fence and a bouncing ball-like object on the inside.
Additionally, I would like to be able to arbitrarily add/remove/redraw the fence in realtime and have the collision detection still operate realistically.
I have considered drawing a Sprite/Shape from the points and doing a HitTest at each frame to check whether to bounce or not.
My question: is this the best/correct way to accomplish this goal? Consider something like JezzBall with diagonal lines of any angle a simulation of what I'm trying to do.
Check the corners of your bouncing ball with four hitTestPoints. If it succeeds, then do hitTestPoints from the fence with shapeflag set to true.
There may be better solutions as I do not know the performance impact of shapeflag, but combined with the corners optimization I think it will be good, but I'm also interested if there is a better way.
Math will be your friend here. Do a quick search for circle-line, or point-line collision (here's one: Circle line-segment collision detection algorithm?).
What you do is run through your array of points, creating lines. So line 1 will be points[0] and points[1], and line 2 will be points[1] and points[2]. After that you check each line against your ball (if you want proper collision that will work no matter the frame rate, then you create a ball line, which is the line that the ball has travelled along between the last frame and this one). Do your collision detection against the ball line and each line made from your points (there's tons of line-line collision detection algos on the web). What you'll get out of an algorithm like that is the time the collision takes place in the current time step, as well as the normal of the colliding line, which will give you the reflection angle.
If you don't know Vector math, then learn it, it'll make your life a ton easier. Again, there are tons of implementations of a Vector2 class on the net.
You can arbitrarily remove parts of the wall as needed by just ignoring those points in your check.
Another lazy solution would be to use a physics engine like Box2D http://box2dflash.sourceforge.net/ or Nape: http://code.google.com/p/nape/ - it might be overkill for what you want for your game, but hey, it's easy.
For bonus points, another technique which might be easier for you is the Separating Axis Theorem, which is used in the flash game N: http://www.metanetsoftware.com/technique.html

Converting Pixels to Bezier Curves in Actionscript 3

Ok, so I'll try to be as descriptive as possible.
I'm working on a project for a client that requires a jibjab-style masking feature of an uploaded image.
I would like to be able to generate a database-storable object that contains anchor/control positions of a bezier shape, so I can pull it out later and re-mask the object. This all is pretty easy to do, except for one catch : I need to create the bezier object from a user-drawn outline.
So far, here's how I imagine the process going:
on mouse down, create a new sprite, beginFill, and moveTo mouse position.
on mouse move, lineTo an XY coordinate.
on mouse up, endFill.
This all works just great. I could just store the info here, but I would be looking at a GIGANTIC object full of tons of pretty useless x/y coordinates, and no way to really make fine-tuning changes outside of putting handles on every pixel. (I may as well give the end user a pencil tool...)
Here's what I'm thinking as far as bezier curve calculation goes :
1: Figure out when I need to start a new curve, and track the xy of the pixel on this interval. I'm imagining this being just a pixel count, maybe just increment a count variable per mouse move and make a new one every x pixels. The issue here is some curves would be inaccurate, and others unnecessary, but I really just need a general area, not an exact representation, so it could work. I'd be happier with something a little smarter though.
2: take each new x/y, store it as an anchor, and figure out where a control would go to make the line curve between this and the last anchor. this is where I get really hung up. I'm sure someone has done this in flash, but no amount of googling can seem to help me out with the way to get this done. I've done a lot of sketching and what little math I can wrap my brain around, but can't seem to figure out a way of converting pixels to beziers.
Is this possible? All I really need is something that will get close to the same shape. I'm thinking about maybe only placing anchors when the angle of the next pixel is beyond 180 degrees in relation to the current line or something, and just grabbing the edge of the arc between these changes, but no matter how hard I try, I can't seem to figure out how to get this working!
Thanks for your help, I'll be sure to post my progress here as I go, I think this could be really useful in many applications, as long as it's actually feasible...
Jesse
It sounds like a lot of work to turn pixels into Bezier curves. You could try using something like the Linear least squares algorithm. http://en.wikipedia.org/wiki/Linear_least_squares
A different tact, could you have your users draw vector graphics instead? That way you can just store the shapes in the database.
Another cool method of converting raster to vector would be something like this iterative program: http://rogeralsing.com/2008/12/07/genetic-programming-evolution-of-mona-lisa/
Good luck
In my answer to this question I discuss using autotrace to convert bitmaps to beziers. I recommend passing your user drawing through this program on the server. Autotrace does a fantastic job of tracing and simplifying so there is no need to try and reinvent the wheel here.
Thanks for the answers, although I guess I probably should be more specific about the application, I'm really only needing an outline for a mask, so converting images to vectors or polygons, despite how cool that is, doesn't really fix my issue. The linear least squares algorithm is mega cool, I think this might be closer to what I'm looking for.
I have a basic workaround going right now, I'm just counting mouse moves, then every X (playing with it to get most desirable curve) moves, I grab the xy position. then, I take every other stored xy, and turn it into an anchor, the remaining xys are turned into controls. This is producing somewhat desirable results, but has some minor issues, in that the speed at which the mask is drawn effects the number of handles, and it's really just getting a general area, not a precise fit.
Interestingly, users seem to draw slower for more precise shapes, so this solution works a lot better than I had imagined, but it's not as nice as it could be. This will work for the client, so although there's no reason to pursue it further, I like learning new things, and will spend some off the clock time looking into linear least equations and seeing if I can drum up a class that will do these computations for me. If anyone runs across some AS3 code for this type of thing, or would like some of mine, let me know, this is an interesting puzzle.