Why doesn't the hitbox of my sprite rotate? How to fix it?
I have a square sprite. I rotate it 45 degrees. Now I want to test when it collides with another object, but the hitbox hasn't tilted, so it registers a hit even when the objects don't seem to be touching.
While this is not the correct way of putting it; the square sort of becomes a diamond (one of its points pointing down) while the hitbox remains开发者_如何学运维 a square (as if it was a cube laying on a table).
var square:Sprite = new Squaresprite(); // a simple sprite formed like a square
square.rotation = 45;
Stage.addChild(square);
square.hitTestObject(someOtherSprite); // can return true even if the sprites don't visibly seem to be touching
It's hard to understand what flash does with these invisible boxes. For instance if you use a container and put sprites in it. I suppose understanding this would make it easier to predict when problems like these would occur.
Is there a simple solution to this that doesn't require me to redraw my Sprite in a rotated position?
Why not make it simple and just use an already-bug-tested and thought out Collision Detection class? Like so: http://evolve.reintroducing.com/2008/10/29/as3/as3-collision-detection-kit/
Basically it comes down to Flash thinking your hitTest or hitTestPoint is on the bounding box of a movieclip/sprite, no matter the rotation. True collision detection goes beyond that (with classes like these).
hitTestObject works with the object's bounding boxes (you can get them with getBounds). However, you can use hitTestPoint and set the 3rd parameter to true (shapeFlag) to tell Flash to use the actual shape of the DisplayObject (including transformations), but as you may guess, it only test them against a single point.
If you need to test just squares you could do this for every corner of every square involved. For two boxes it would only take 8 tests (which wouldn't take much cpu time), but with too many boxes you may want to filter possible hits through hitTestObject or other techniques (grids, etc...).
For more complex shapes, you will need much more complex calculations and/or techniques, in which case I would definitely go with jpea's answer ;)
It sounds like the hit test is using the axis aligned bounding box of the object which will be as you describe. This is a relatively quick test as the maths involved is relatively simply - do the x
and y
values lie in the target range.
You will need to make your code more "intelligent".
Use the bounding box as the first approximation yes/no test. If the bounding box doesn't interact with the target then you can be sure that the object won't so you can discard this target straight away. If the bounding box does interact then you will need to do some more complex tests.
精彩评论