Simple physics

This is a simple code to play with physics.

//time
int lastMillis = 0;

//character
float positionX = 1;
float positionY = 1;
float sizeX = 0.1;
float sizeY = 0.1;
float velocityX = 0.0;
float velocityY = 0.0;
float gravity = 0.1;
boolean onGround = false;
float jumpSpeed = 0.06;
float moveSpeed = 0.002;

//world
float floorFriction = 0.1;
float airFriction = 0.1;
float depreciser = 0.0005;
int worldHeight = 2;
int worldWidth = 2;
int worldScale = 500;
float bounciness = 0.7;


int deltaTime() //time in milliseconds between each frames
{
  int delta = millis() - lastMillis;
  lastMillis = millis();
  return delta;
}

//you can override this
boolean canJump() { return onGround;}

void inputs() 
{
  //jump
  if (mousePressed && canJump())
  {
    velocityY -= jumpSpeed;
  }
  if (keyPressed)
  {  
    //move left
    if(key == 'a'|| key == 'A' || key == 'q'|| key == 'Q' ) {
    velocityX -= moveSpeed;
    }
    //move right
    if(key == 'd' || key == 'D') {
      velocityX += moveSpeed;
    }
    //jump
    if(key == ' ' && canJump()) {
      velocityY -= jumpSpeed;
    }
  } 
}

void setup() 
{
  size(worldWidth * worldScale, worldHeight * worldScale);
}

void draw() 
{
  float deltaTime =  ((float)deltaTime())/1000.0;

  //gravity
  velocityY += gravity*deltaTime;

  //inputs
  inputs();

  //airFriction
    velocityX -= airFriction*moveSpeed * velocityX;
    velocityY -= airFriction*moveSpeed * velocityY;

 //floor friction
  if (onGround)
  {
      velocityX -= floorFriction * velocityX;
  }

  if (abs(velocityX) <= depreciser) velocityX = 0;

  //set new position
  positionX += velocityX;
  positionY += velocityY;

  //hits
  //hit ground
  if (positionY + sizeY/2 >= worldHeight) 
  {
    positionY = worldHeight - sizeY/2;
    velocityY = -velocityY*bounciness;
    onGround = true;
  } else
  {
    onGround = false; 
  }
  //hit walls
  if (positionX + sizeY/2 >= worldWidth || positionX - sizeY/2 <= 0) 
  {
    if (positionX + sizeY/2 >= 2) 
    {
      positionX = worldWidth - sizeY/2;
    }

    if (positionX - sizeY/2 <= 0) 
    {
      positionX = 0 + sizeY/2;
    }
      velocityX = -velocityX*bounciness;
  }

 //draw
  background(0);
  noStroke();

  fill(102);
  rect((positionX - sizeX/2) * worldScale, (positionY - sizeY/2) * worldScale, sizeX * worldScale, sizeY * worldScale);

}
Tagged:

Comments

Sign In or Register to comment.