출처 : http://www.rodedev.com/tutorials/gamephysics/game_physics.swf
// set initial angle and speed var angle = 30; var speed = 20; // calcuate x, y scales (this will give the x/y equivalent of the angle) var scale_x = cos(angle); // the x scale is the sin of the angle var scale_y = sin(angle); // the y scale is the sin of the angle var velocity_x = (speed * scale_x); // speed times scal_x is our x velocity var velocity_y = (speed * scale_y); // speed times scale_y is our y velocity // each frame call game loop to set object's position(move it along the predefined angle) function GameLoop() { movingObject.x = movingObject.x + velocity_x; movingObject.y = movingObject.y + velocity_y; }//end game loop
// set initial angle and speed, acceleration var angle = 30; movingObject.speed = 20; movingObject.acceleration = 2; // calcuate x, y scales (this will give the x/y equivalent of the angle) var scale_x = cos(angle); // the x scale is the sin of the angle var scale_y = sin(angle); // the y scale is the sin of the angle // each frame call game loop to set object's position(move it along the predefined angle) function GameLoop() { // continously add acceleration to speed movingObject.speed = movingObject.speed + movingObject.acceleration; // speed times scale_x, scale_y is our x/y velocity movingObject.velocity_x = (movingObject.speed * scale_x); movingObject.velocity_y = (movingObject.speed * scale_y); movingObject.x = movingObject.x + movingObject.velocity_x; movingObject.y = movingObject.y + movingObject.velocity_y; }//end game loop
// set gravity constant var gravity = 3; var moving = true; // each frame call game loop to set object's position function GameLoop() { if( moving == true ) { velocity_y = velocity_y - gravity; // if object has not hit the ground add y velocity(may be a negative velocity) if( movingObject.y - velocity_y > ground.y ) { movingObject.y = movingObject.y + velocity_y; } movingObject.x = movingObject.x + velocity_x; } }
오브젝트를 던지거나 패스하는 경우,
코드 예제
function GameLoop() { if( thrown == true && moving == false ) { moving = true; // get distance between two guys var distance = guy2.x - guy1.x; // claculate x and y velocities velocity_y = time * gravity * 0.5; velocity_x = distance / time; } // .... if( moving == true ) { ball.x = ball.x + velocity_x; ball.y = ball.y + velocity_y; velocity_y = velocity_y - gravity; } }