S1syphus
S1syphus

Reputation: 1441

Detecting Collisions in Flash... or a better way of doing it

I'm trying to create a air-hockey game, in flash using AS3.

At the moment, I am using an enter frame function to check the positioning of the 3 objects, 2 paddles and a ball, then it checks to see if they are in contact, if they are it then initiates a detect collision function.

However it's checking every time the frame is loaded, and at 25 fps, this is quite a lot and the app lags.

Any ideas, or better ways to do this?

Thanks in advance.

Upvotes: 0

Views: 1302

Answers (3)

Chris Burt-Brown
Chris Burt-Brown

Reputation: 2727

Two pythagoras statements are slowing your game down? At 25fps? Something is wrong -- that should not be the case.

Remove the collision detection completely and check that you get your 25fps back, then add statements a line at a time until the slowdown reappears.

Check you are not calling your collision code more than once (well, twice) per frame.

Remember that you can test for collision without using Math.sqrt:

function circlesTouching(circle1:Point, circle1Radius:Number, circle2:Point, circle2Radius:Number):Boolean {
    var dx:Number = circle1.x - circle2.x;
    var dy:Number = circle1.y - circle2.y;
    var minDist:Number = circle1Radius + circle2Radius;
    return (dx*dx) + (dy*dy) < (minDist * minDist);
}

(You will still need sqrt to resolve the collision but this should be pretty rare.)

However in my experience, even though Math.sqrt is the slowest part of Pythagoras, it's still easily fast enough to manage two calls per frame at 25fps. It sounds like something else is wrong.

Upvotes: 1

Roy
Roy

Reputation: 325

Have you tried a timer?

var timer:Timer = new Timer(250); // 4 times a second

timer.addEventListener(TimerEvent.TIMER, onTimer);
timer.start();


private function onTimer(ev:TimerEvent):void
{
  checkCollision();
}

Upvotes: 1

Lars Bl&#229;sj&#246;
Lars Bl&#229;sj&#246;

Reputation: 6127

If you need to check something periodically, I guess the enterFrame event is a suitable mechanism to do it.

You don't mention if you use the built-in hit test functions or not, so I thought I'd mention them: hitTestObject and hitTestPoint.

Upvotes: 1

Related Questions