I was bored today, and thought about how cool it would be if I could make an earth-gravity simulation for bouncing objects in 2D...so I did.
#include "DarkGDK.h"
float scaleFactor=1; // 1 is recommended
int dampening=3;
int timeScale=1;
int timed,timeSet;
int groundLevel=590;
int bouncePower=-100;
char szTemp[50];
typedef struct controlSytem{
int x,y,w,h,id,timeOut;
float vel;
bool offGround;
bool bouncy;
}physObject;
void DarkGDK(void){
dbSetWindowOn();
dbSetWindowTitle("Real-World Bounce Demo");
dbSetDisplayMode(800,600,32);
dbSetWindowSize(800,600);
dbSyncOn();
dbSync();
dbBackdropOff();
//Create physics 'object'
physObject box;
box.id=1;
box.x=dbScreenWidth()/2-25;
box.y=500;
box.w=box.h=50;
box.bouncy=true;
dbCreateBitmap(box.id,box.w,box.h);
dbSetCurrentBitmap(box.id);
dbInk(dbRGB(255,255,255),dbRGB(0,0,0));
dbBox(0,0,box.w,box.h);
dbGetImage(box.id,0,0,box.w,box.h);
dbSetCurrentBitmap(0);
dbDeleteBitmap(box.id);
dbSprite(box.id,box.x,box.y,box.id);
dbWait(1000);
static bool spaceKeyCatch=false;
static bool upKeyCatch=false;
static bool downKeyCatch=false;
int init=1;
while(LoopGDK()){
timeSet=dbTimer();
if(box.y<groundLevel-box.h)box.offGround=true;
if(box.y>=groundLevel-box.h){
if(init==1){
init=0;
box.vel=0;
}
box.offGround=false;
box.y=groundLevel-box.h;
if(box.bouncy)box.vel=-box.vel/dampening;
if(!box.bouncy)box.vel=0;
box.timeOut=0;
}
if((dbSpaceKey()==0)&&(spaceKeyCatch))spaceKeyCatch=false;
if((dbSpaceKey()==1)&&(!spaceKeyCatch)){
spaceKeyCatch=true;
if(!box.offGround)box.vel=-bouncePower*scaleFactor;
}
if((box.vel<2)&&(box.vel>-2))box.vel=0;
if((dbUpKey()==0)&&(upKeyCatch))upKeyCatch=false;
if((dbUpKey()==1)&&(!upKeyCatch)){
upKeyCatch=true;
bouncePower-=10;
}
if((dbDownKey()==0)&&(downKeyCatch))downKeyCatch=false;
if((dbDownKey()==1)&&(!downKeyCatch)){
downKeyCatch=true;
bouncePower+=10;
}
box.timeOut+=timed;
box.vel+=(9.8*box.timeOut)/1000;
box.y+=box.vel/scaleFactor;
if(!box.offGround){
if(dbLeftKey()==1)box.x--;
if(dbRightKey()==1)box.x++;
}
if(box.x<=0)box.x=0;
if(box.x>=dbScreenWidth()-box.w)box.x=dbScreenWidth()-box.w;
dbSprite(box.id,box.x,box.y,box.id);
//Timing
dbSync();
timed=dbTimer()-timeSet;
dbCLS();
dbInk(dbRGB(255,255,255),dbRGB(0,0,0));
if(!box.offGround){
dbCenterText(400,200,"Press Space to Bounce");
}
dbInk(dbRGB(255,0,0),dbRGB(0,0,0));
sprintf(szTemp,"Bounce power: %d",-bouncePower);
dbText(0,0,szTemp);
}
return;
}
I did this in about an hour, so understand that it's sloppy. What do you guys think? (Parts may seem unnecessarily complicated, like the use of a typdef. This is because I want to be able to build from this into a pure C++/DarkGDK physics engine that doesn't require a library.)
EDIT: You can now adjust the power of the bounce with up and down arrow keys.
My site, for various stuff that I make.