See how this grabs you. I abstracted the roid ship into its own little class called (for no good reason) "Squar."
Doing it this way, IMO, makes the relationships between pieces more obvious
// roidulous - asteroid ship, bjorke 27 sep 2010
class Squar {
PVector pos;
PVector vel;
float direction; // in radians
Squar() {
pos = new PVector(120.0,120.0);
vel = new PVector(0.0,0.0);
direction = 0.0; // only changes instantaneously -- no rotation momentum!
}
void UpdatePos() {
pos.x += vel.x;
pos.y += vel.y;
}
void Brake(float Drag) { // used for decay and speed limiting both
vel.x *= Drag;
vel.y *= Drag;
}
void Clip() { // "toroidal" clip
float margin = 5.0; // tune to taste
float farX = width - margin;
float farY = height - margin;
if (pos.x < margin) {
pos.x = farX - (margin - pos.x);
} else if (pos.x > farX) {
pos.x = margin + (pos.x-farX);
}
if (pos.y < margin) {
pos.y = farY - (margin - pos.y);
} else if (pos.y > farY) {
pos.y = margin + (pos.y-farY);
}
}
void Accelerate(float thrust) {
vel.x += thrust * cos(direction);
vel.y += thrust * sin(direction);
}
void Rotate(float Angle) {
direction += Angle;
}
void ValidateSpeed() { //added to keep things sane
float maxFrac = 0.1; // how much of the screen to traverse - max - per frame
float maxX = width * maxFrac;
float maxY = height * maxFrac;
if (abs(vel.x) > maxX) {
float braking = maxX / vel.x;
Brake(braking);
}
if (abs(vel.y) > maxY) {
float braking = maxY / vel.y;
Brake(braking);
}
}
void Draw()
{
pushMatrix();
translate(pos.x,pos.y);
rotate(direction);
quad(8.0,0.0, -4.0,4.0, -1.0,0.0, -4.0,-4.0);
popMatrix();
}
};
// global variables
Squar blah;
// tune these to taste
float decay = .985;
float keyRot = radians(5.0);
float keyThrust = 0.5;
////// actual code ////
void setup() {
size(500,500);
frameRate(60);
blah = new Squar();
}
void draw() {
background(125);
blah.UpdatePos();
blah.Clip();
blah.Brake(decay);
blah.ValidateSpeed();
blah.Draw();
}
void keyPressed() {
// note that this will be sensitive to your
// system key-repeat settings, and that only one
// key can be pressed at a time!
if (key == 'h') {
blah.Rotate(keyRot);
} else if (key == 'k') {
blah.Rotate(-keyRot);
} else if (key == 'u') {
blah.Accelerate(keyThrust);
}
}
kb, Trion Worlds