Page 1 of 1

[C++/DarkGDK]Gravity Simulation

Posted: Mon Jun 22, 2009 2:18 pm
by zapakitul
A small piece of code i did not to long ago, that "simulates" the earth gravity! Kinda buggy, but maybe someone will find it useful.
Utub Link

Code: Select all

#include "DarkGDK.h"
#include "SC_Collision.h"
#include "math.h"

void MovementSiColliziune();


float gravity = -0.28f;
float radius = 2;
float radious = 1;
int playervar = 2;
float playerspeed = 0.3;
float speed = 0;
float px;
float py;
float pz;
float dist;
float G = 6.67428 * pow(10.0,-11);
float acceleration;
void DarkGDK ( void )
{
	dbSyncOn   ( );
	dbSyncRate ( 60 );
	dbSetDisplayModeAntialias(1024,768,32,1,4,0);
	dbAutoCamOff();
	SC_Start( );

	//World - 1
	dbMakeObjectSphere(1,50);
	SC_SetupComplexObject(1,1,2);
	//dbGhostObjectOn(1);
	//Player - 2
	dbMakeObjectCube(playervar,radius);
	dbPositionObject(playervar,dbObjectPositionX(1),dbObjectPositionY(1)+30,dbObjectPositionZ(1));

	SC_SetupObject(playervar,0,0);

	//Debug Object
	dbMakeObjectCube(5,1);
	dbColorObject(5,dbRGB(255,0,0));
	dbPositionObject(5,dbObjectPositionX(1),dbObjectPositionY(1)+30,dbObjectPositionZ(1));
	SC_SetupObject(5,0,0);
	while ( LoopGDK ( ) )
	{
		MovementSiColliziune();
	dbControlCameraUsingArrowKeys(0,0.7,0.7);

		dbSync ( );
	}

	return;
}

void MovementSiColliziune()
{

	float oldx = dbObjectPositionX(playervar);
	float oldy = dbObjectPositionY(playervar);
	float oldz = dbObjectPositionZ(playervar);
	
	if(dbKeyState(17))
	{
		dbMoveObject(playervar,playerspeed);	
	}
	if(dbKeyState(31))
	{
		dbMoveObject(playervar,-playerspeed);
	}
dbPositionObject(5,dbObjectPositionX(playervar),dbObjectPositionY(playervar),dbObjectPositionZ(playervar));

px = dbObjectPositionX(1)-dbObjectPositionX(playervar);
py = dbObjectPositionY(1)-dbObjectPositionY(playervar);
pz = dbObjectPositionZ(1)-dbObjectPositionZ(playervar);
dist = (px*px)+(py*py)+(pz*pz);   
acceleration = 0-(20000000000*G)/dist;
speed-=acceleration;

dbPointObject(5,dbObjectPositionX(1),dbObjectPositionY(1),dbObjectPositionZ(1));
dbMoveObject(5, speed);
dbPositionObject(playervar,dbObjectPositionX(5),dbObjectPositionY(5),dbObjectPositionZ(5)); 

	float newx = dbObjectPositionX(playervar);
	float newy = dbObjectPositionY(playervar);
	float newz = dbObjectPositionZ(playervar);

	int collide = SC_SphereSlideGroup( 1, oldx,oldy,oldz, newx,newy,newz,radious, 0 );
	if(collide)
	{ 
		dbPositionObject(playervar,SC_GetCollisionSlideX(),SC_GetCollisionSlideY(),SC_GetCollisionSlideZ());
speed = 0;
	}


	
	if(dbKeyState(30))
	{
		dbTurnObjectLeft(playervar,1);
	}

	if(dbKeyState(32))
	{
		dbTurnObjectRight(playervar,1);
	}
	if(dbSpaceKey())
	{
		dbPitchObjectUp(playervar,1);
	}
	if(dbReturnKey())
	{
		dbPitchObjectDown(playervar,2);
	}


}