Max speed

edited October 2013 in Programming Questions

How can I set a maximum speed?

float shipAngle;
float shipX, shipY;
float shipSpeed;
float bulletAngle;
float bulletX, bulletY;
float bulletSpeed;

void setup() {
  size(400, 400);

  shipAngle = 0.0;
  shipX = width/2;
  shipY = height/2;
  shipSpeed = 5.0;

  bulletAngle = 0.0;
  bulletX = -100;
  bulletY = -100;
  bulletSpeed = 5.0;
}

void draw() {
  background(0);
  stroke(255);

  pushMatrix();
    translate(bulletX, bulletY);

    // Display the bullet
    fill(255);
    ellipse(0, 0, 2, 2);
    moveBullet();
  popMatrix();

  pushMatrix();
    // Translate ship origin to (shipX, shipX)
    translate(shipX, shipY);

    // Rotate ship based on angle of rotation
    rotate(radians(shipAngle));

    // Display the ship
    fill(7,88,16);
    beginShape();

    endShape(CLOSE);
  popMatrix();
}

void keyPressed() {
  if (keyCode == UP) {
    // forward
    shipSpeed = 10;
    moveShip();
  }
  else if (keyCode == DOWN) {
    // back
    shipSpeed = -2;
    moveShip();
  }
  else if (keyCode == LEFT) {
    shipAngle = shipAngle - 10;
  }
  else if (keyCode == RIGHT) {
    shipAngle = shipAngle + 10;
  }
  else if (keyCode == ' ') {
    bulletX = shipX;
    bulletY = shipY;
    bulletAngle = shipAngle;
  }
}

void moveShip() { 
  // get polar coordinates where 
  // theta = angle and r = speed
  shipX = shipX + shipSpeed*cos(radians(shipAngle));
  shipY = shipY + shipSpeed*sin(radians(shipAngle));
}

void moveBullet() {
  bulletX = bulletX + bulletSpeed*cos(radians(bulletAngle));
  bulletY = bulletY + bulletSpeed*sin(radians(bulletAngle));
}

}

Answers

Sign In or Register to comment.