Make the object move in the circle (asteroids game)

Okay. This took a lot of fiddling to get right.

class Ship {
  PVector p, v;
  float a;
  float da = 0;
  Ship() {
    p = new PVector( width/2, height/5 );
    v = new PVector( 3, 0 );
  }
  void draw() {
    simulate();
    render();
  }
  void simulate() {
    if ( key_down[2] ) { // LEFT
      da = -radians(1);
    }
    if ( key_down[3] ) { // RIGHT
      da = radians(1);
    }
    if ( key_down[1] ) { // DOWN
      da = 0;
    }
    a = atan2(v.y,v.x);
    
    v.x=3*cos(a+da);
    v.y=3*sin(a+da);
    
    p.x+=v.x;
    p.y+=v.y;
  }
  void render() {
    fill(255);
    translate(p.x, p.y);
    rotate(a);//map(millis()%7000,0,7000,0,TWO_PI));
    noStroke();
    quad(20, 0, -20, 10, -10, 0, -20, -10);
  }
}

Ship ship;

void setup() {
  size(1000, 1000);
  ship = new Ship();
}

void draw() {
  background(0);
  ship.draw();
}


char[] tracked_keys = { UP, DOWN, LEFT, RIGHT };
boolean[] key_down = { false, false, false, true };

void keyPressed() {
  keyTrack(true);
}

void keyReleased() {
  keyTrack(false);
}

void keyTrack(boolean b) {
  for ( int i = 0; i < tracked_keys.length; i++) {
    if ( keyCode == tracked_keys[i] ) {
      key_down[i] = b;
    }
  }
}

NOTE: I set the RIGHT key_down to true so the ship starts to turn immediately (for debug reasons, to keep the ship on the screen normally) - you’ll have to tap the right arrow to get controlling it properly.

2 Likes