PDA

View Full Version : Help with Gravity and Inertia



JapanMan
December 12th, 2008, 03:07 PM
I found an excellent tutorial on this, where you control a little ball with the arrow keys. Unfortunately, I can't find the the site anymore (it may be blocked b/c im not on my home PC). Basically, you were falling by default, and the longer you fell, the faster you did and the harder it was to move up again; this is very much like the "physics" in those helicopter games. I have been looking for this a lot, and was hoping someone could direct me to it or teach me.

bluemagica
December 12th, 2008, 11:30 PM
umm...i don't know how indepth concept that tutorial had, but what you said seems to be quite simple!

if(up is pressed)
{
fspeed-=1;
}
else
{
fspeed+=0.5;
}
helicopter.y+=fspeed;


this is the most simplest way to do what you are saying!

therobot
December 13th, 2008, 12:34 AM
To expand on what Bluemagica said, for every object you want to be affected by physics, you can set up a few simple variables:



var PhysicsObject:Object = new Object();
// velocity on x axis
PhysicsObject.vx 0;
// velocity on y axis
PhysicsObject.vy = 0;
// acceleration on x axis
PhysicsObject.ax = 0;
// acceleration on y axis
PhysicsObject.ay = 0;


Keep some global properties:



var Wind:Number = 0.1;
var Gravity:Number = 0.1;


Now basically, on EnterFrame, you will want to add Wind to the objects x acceleration, and add gravity to it's y acceleration. then, add the acceleration variables to their respective velocities. From there, add their velocities to their respective x and y coordinates. If the user is holding a key down that could cause the object to slow down, adjust its acceleration



onEnterFrame = function()
{
// calculate acceleration based on external forces
PhysicsObject.ax += Wind;
PhysicsObject.ay += Gravity;

// if the user is applying the brakes, adjust the y acceleration based on their Brake speed you can define elsewhere.
if ( Braking ) PhysicsObject.ay += BrakingSpeedY;

// calculate velocity based on acceleration
PhysicsObject. vx += PhysicsObject.ax;
PhysicsObject.vy += PhysicsObject.ay;

// calculate x and y position based on velocity
PhysicsObject.x += PhysicsObject.vx;
PhysicsObject.y += PhysicsObjetc.vy;
}


I know you asked just for gravity, but why not throw in some wind :)