giovedì 9 agosto 2012

Simple game/physics engine in Processing

Today i'm posting about a simple physics engine that I made in processing, I think there are some bugs but it's good to start a 2D game engine.
Here is the code:
Block b1;
Rectc c;
Boolean collision = false;
Boolean jumping = false;

void setup(){
  size(600, 400);
  c = new Rectc(40.0, float(height)-100);
  b1 = new Block(20.0, float(height)-50);

  }

void draw(){
  background(255);
  c.update();
  b1.update();
  println(jumping);
  }

class Block{
  float xpos, ypos;
  Block(float x, float y){
    xpos = x;
    ypos = y;
    }
  void update(){
    fill(255, 0, 0);
    rect(xpos, ypos, 50, 50);
    if(c.ypos >= ypos-20 && (c.xpos+10 >= xpos && c.xpos+10 <= xpos+50)){
      collision = true;
      jumping = false;
      }
    else{
      collision = false;
      }
    }
  }

class Rectc{
  float xpos, ypos;
  float vx = 0;
  float vy = 0;
  float elasticy = 0.4;
  Rectc(float x, float y){
    xpos = x;
    ypos = y;
    }
  void update(){
    if(keyPressed){
      if(jumping != true && key =='w'){
        vy += -15;
        jumping = true;
      }
      if(key =='a'){
        vx += -1;
        }
      if(key == 'd'){
        vx += 1;
        }
      if(key == 's'){
        vy += 0.25;       
        }
    }
    xpos += vx;
    ypos += vy;
    vx *= 0.4;
    vy *= 0.99;
    vy += 0.25;
    if(collision){
      vy = -Math.abs(vy);
      vy *= elasticy;
      ypos += vy;
      }
    fill(0, 255, 0);
    rect(xpos, ypos, 20, 20);
    }
  }

The code is available for download here(.zip).
If you have any questions about the code please comment or send me an e-mail to damianoandre@gmail.com

I hope you enjoy this post!
Bye, Dami

Nessun commento:

Posta un commento