user3045711
user3045711

Reputation:

AS3 - hitTestObject object hovering?

I'm trying to build a 2d game in actionscript 3.0, but I am having problems with the hittest. I have got this code here

import flash.ui.Keyboard;
import flash.events.Event;
import flash.events.KeyboardEvent;

myChar.addEventListener(Event.ENTER_FRAME, update);
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);
stage.addEventListener(KeyboardEvent.KEY_UP, onKeyUp);
stage.addEventListener(Event.ENTER_FRAME, letsSee);

var keys:Array=[];

function update(e:Event):void {
    myChar.y+=10;
        if (keys[Keyboard.RIGHT]) {
            myChar.x+=10;
        }

        if (keys[Keyboard.LEFT]) {
            myChar.x-=10;
        }
}

function onKeyDown(e:KeyboardEvent):void {
    keys[e.keyCode]=true;
}

function onKeyUp(e:KeyboardEvent):void {
    keys[e.keyCode]=false;
}
function letsSee(e:Event):void {
    if (myChar.hitTestObject(myLevel)==true) {
        myChar.y-=10;
    }
}

And everything works just fine, but the hitTestObeject in the letsSee function doesn't work as I want it, I want my character (myChar) to be spot on the platoe (myLevel) but myChar keeps hovering.

How do I make hitTestObject with out object hovering?

Upvotes: 0

Views: 193

Answers (1)

TreeTree
TreeTree

Reputation: 3230

It's hovering because you're lifting him up at the same rate as he is falling when there's a collision.

Imagine the character starts at 5 and the object is at 20. In 2 frames the character will be at 25 which collides with the object. When this happens you move him up by 10 which puts him at 15, so he's hovering above by 5. Then in the next frame the exact same thing happens. Thus he will always be hovering.

One solution is to move the character up by the amount that he is "inside" the object. So if he is at 23 and the object is at 20, you move him up by 3.

Another solution which is far from the most efficient but is the easiest to do, in my opinion, is this

function letsSee(e:Event):void {
    while (myChar.hitTestObject(myLevel)==true) {
        myChar.y-=1;
    }
}

This will repeatedly move him up by one until he is no longer colliding with the object.

Note: What I discovered with the hitTestObject method is that it counts as a collision if the two boxes' edges are in the same spot. Example:

Box A is 100x100 and is at x=100, y = 100 Box B is 100x100 and is at x=200, y = 100 hitTestObject will count that as colliding, if B was at x=201 then it won't count.

Upvotes: 1

Related Questions