How can I create object collision for a game? AS3
Copy link to clipboard
Copied
Hi all, I'm struggling heaps trying to create collision detection for my game. I've tried a million ways going about the code, but I need the simplest way of doing it:
By the way, I need the code to be in a Class file for Actionscript 3
Just for simplicity
let's say I have two movieclips
ball1
ball2
I want to give keyboard properties to ball 1, which allows it to move UP, DOWN, LEFT, RIGHT
I want ball2 to be the object that if ball1 touches it, it pushes the ball1 a few steps back in the x coordinate position
So basically, what is the code for
Having ball1 being able to move around the screen, and if it comes into contact with ball2, it will push ball1 back? (ball2 is stationary)
This would be a tremendous amount of help, as I'm trying to create a game for a final project, and I'm having the hardest time in doing so, helping with this will totally allow me to understand what to do, and I can hopefully take it from there
Thanks so much!
Copy link to clipboard
Copied
// in your keyboard setup function:
stage.addEventListener(KeyboardEvent.KEY_DOWN,keydownF);
stage.addEventListener(KeyboardEvent.KEY_UP,keyupF);
// in your game start function:
this.addEventListener(Event.ENTER_FRAME,enterframeF);
// in this class:
private function enterframeF(e:Event):void{
if(ball1.left){
ball1.x-=speed; //assuing you're using a speed variable
} else if(ball1.right){
ball1.x+=speed;
}
if(ball1.up){
ball1.y-=speed;
} else if(ball1.down){
ball1.y+=speed;
}
if(ball1.hitTestObject(ball2)){
ball1.x-=whatever;
}
}
private function keydownF(e:KeyboardEvent):void{
switch(e.keyCode){
case 37:
ball1.left=true;
break;
case 38:
ball1.up=true;
break;
case 39:
ball1.right=true;
break;
case 40:
ball1.down=true;
break;
}
}
private function keyupF(e:KeyboardEvent):void{
switch(e.keyCode){
case 37:
ball1.left=false;
break;
case 38:
ball1.up=false;
break;
case 39:
ball1.right=false;
break;
case 40:
ball1.down=false;
break;
}
}

