actionscript-3flashflash-cs6flash-cc

Moving away object when hit each other


I don't wanna to overlap each other the objects.Also I wanna keep the objects in stage limit.The buttons must move away when hit each other.I tried hitTestObject but buttons move like this.

Sample move code for fish 2 *UPDATE

var fish2x:Number=10;
var fish2y:Number=14;
 
stage.addEventListener(Event.ENTER_FRAME,h42);
function h42(s:Event = null) {
fish2.x+=fish2x;
fish2.y+=fish2y;
if ((fish2.x>=stage.stageWidth-fish2.width/2)|| (fish2.x <= fish2.width/2 )) {
    fish2x*=-1;
}
if ((fish2.y>=stage.stageHeight-fish2.height/2)|| (fish2.y <= fish2.height/2 )) {
    fish2y*=-1;
}

if (fish2.hitTestObject(fish3)){
fish2y *= -1;
fish3y *= -1;
h42();
}
}

Also I tried in diffrent function

stage.addEventListener(Event.ENTER_FRAME,crash);
function crash(s:Event) {
 
if (fish2.hitTestObject(fish || fish3 )) {

fish2y*=-1;
message.text="crash";
}
}

For more than 2 fish not work. I set null fish2 and fish 3 than I use this code.

if (fish2.hitTestObject(fish3 || fish4)){
fish2y *= -1;
fish2x *= -1;
h42();
 }

I changed hittestoject all off them.All function change like this but it not work.

Update 2

Now it's no error,but not happens when fish3 hit each other.I removed "null" fish and fish 3 just used for fish 2.

        if (fish2.hitTestObject(fish || fsih3)){
fish2y *= -1;
fish2x *= -1;
fishy*=-1;
fishx*=-1;
fish3y*=-1;
fish3x*=-1;
}
}

Solution

  • I think it is because they are both moving. When you check collisions between A and B Fishes, if the collision is true, don't just change their speed by *=-1. Instead, also move them one time.

    if (A.hitTestObject(B)){
        Ay *= -1;
        Ax *= -1;
        By *= -1;
        Bx *= -1;
        h42();
    }
    

    and add null to your default value like this:

    function h42(s:Event = null) {