PDA

View Full Version : Gravity and Collision in CS4


Me2LoveIt2
09-14-2009, 10:08 PM
I worked on a new Flash project, but I cant seem to find a good solution for how I want my objects to collide.

In my project I have: a Ball(moving object) and a Floor(not moving).

The ball is positioned over the floor and drops onto the floor through the gravity that is applied with the code.

Code:

var gy:Number = 0;
var gravity:Number = .2

function ballMovement(event:Event):void{
if(ball_mc.hitTestObject(floor_mc)){
ball_mc.y = floor_mc.y-23 //the -23 is because the ball has a diameter of 46 and seems to me calculating from //the middle, i figured this out through trial and error
gy=0 //set the gravity to zero once it is on the floor, so it stops moving
} else { //this part does the gravity
gy+=gravity;
ball_mc.y+=gy;
}
};

this.addEventListener(Event.ENTER_FRAME, ballMovement);

My problems are these.

First: the -23 in the code is what I don't like.

Second: every single object that deals with collisions would need to be put into the if statement.

Bottom line:
I Don't like this code!

Is there a way to have a global gravity in flash AS3. In which you could choose what objects you want to be affected by it?

Is there a way to have a block of code that separates moving from still objects and will not let any objects collide(not overlap)?

UncleNinja
09-15-2009, 03:38 PM
Hello there! :)
I'm no expert on this, but nobody else seems intrested in helping you, so I might as well.
A very good idea is to put all your objects in an array and cycle through them in your enter frame handler.
For example, look at this code:
var sceneObjects:Array=new Array(bob, larry);
var gravitySpeed:Number=5;

stage.addEventListener(Event.ENTER_FRAME, gravity);

function gravity(e:Event){
for(var i:int=0; i<sceneObjects.length; i++){
if(sceneObjects[i].y+sceneObjects[i].height+5 <= stage.stageHeight){
sceneObjects[i].y+=5;
}
}
}How this works is you have two objects, bob and larry, which you cycle through to see if they can by moved down. This is gravity.

Just try that. :)