Monday, January 20, 2014

Project demo



import processing.serial.*;            
import java.awt.Rectangle;


Serial myPort;  
                     
String portNumber = "";  

int xPos = 100;
int yPos = 100;
float xAccel, yAccel;
int shipHeight = 50;
int shipWidth = 60;
float shipAngle = 0;

Rectangle ship;
int bulletCount = 5;
Bullet[] bullets;
int rateOfFire = 0;
int nextShot = 0;

void setup()
{
 
  size(displayWidth, displayHeight);
  ship = new Rectangle(xPos, yPos, shipWidth, shipHeight);

  println(Serial.list());
 
  myPort = new Serial(this, Serial.list()[0], 9600);
  myPort.bufferUntil('\n');
 
  bullets = new Bullet[10];
  for(int i = 0; i < bullets.length; i++)
  {
    bullets[i] = new Bullet();
  }
 
}

void draw()
{
  //ellipseMode(CENTER);
  background(255);
  //fill(255);
  rectMode(CENTER);
  fill(100);
  translate(ship.x,ship.y);
  rotate(shipAngle);
  translate(-ship.x,-ship.y);
  rect(ship.x, ship.y, ship.width, ship.height);
  translate(ship.x,ship.y);
  rotate(-shipAngle);
  translate(-ship.x,-ship.y);
 
  bulletUpdate();
}




void bulletUpdate()
{

  for(int i = bullets.length-1; i >=0; i--)
  {
    if(bullets[i].alive == true)
    {
      bullets[i].update();
      bullets[i].display();
      print("bullet "+i+" is "+bullets[i].alive);
    }
    else
    {
      nextShot = i;
    }
  }
 
}

void serialEvent(Serial thisPort) {
 
   String inputString = thisPort.readString();
 
   inputString = trim(inputString);
 
   int sensors[] = int(split(inputString, ','));
 
   if(rateOfFire > 0)
   {
     rateOfFire--;
   }
   //if(thisport == myPort && myPort != null)
   //{
     if (sensors.length == 5) {
          ship.x = ship.x + (-1*int(map(sensors[0], -200, 220, -5, 5)));
          ship.y = ship.y + int(map(sensors[1], -180, 220, -5, 5));
          shipAngle = atan2(sensors[2],sensors[3]);
          //print("button press: " + sensors[4]);
          if(sensors[4] == 0)
          {
            bullets[nextShot].fired(ship.x,ship.y,shipAngle);
            rateOfFire = 500;
          }
     }
   //}
 
}


class Bullet
{
 
 int xPos = 0;
 int yPos = 0;
 float angle;
 int speed = 10;
 int lifeSpan = 200;
 int bulletSize = 10;
 boolean alive = false;


  void update()
  {
    if(alive == true)
    {
      xPos = xPos + int(cos(angle)*speed);
      yPos = yPos + int(sin(angle)*speed);
      lifeSpan--;
      if(lifeSpan <= 0)
        alive = false;
    }
  }
   
  void fired(int x, int y, float ang)
  {
      alive = true;
      lifeSpan = 200;
      xPos = x;
      yPos = y;
      angle = ang-(PI/2);
  } 
  
  void display()
  {
    if(alive == true)
    {
      ellipseMode(CENTER);
      translate(xPos,yPos);
      rotate(angle);
      translate(-xPos,-yPos);
      ellipse(xPos, yPos, bulletSize, bulletSize);
      translate(xPos,yPos);
      rotate(-angle);
      translate(-xPos,-yPos);
    }
  }
}

No comments:

Post a Comment