Asteroids
in
Programming Questions
•
10 months ago
I'm working on an Asteroids clone, but I'm having trouble when it comes to movement. I got the player to move properly, but then I realized that in Asteroids, when you stop moving forwards, you drift in the same direction, and can turn on the spot without moving in a different direction (hopefully you understand this). Can anybody help me with this?
Relevant class files:
- Player player;
- Factory factory = new Factory();
- ArrayList enemies = new ArrayList();
- boolean upReleased = true;
- int score;
- boolean show;
- boolean keys[] = new boolean[512];
- void setup() {
- size(screen.width-300, screen.height);
- smooth();
- player = new Player();
- factory.newEnemy();
- }
- void draw() {
- background(0);
- text("Score: "+score, 0, 10);
- player.update();
- if (keys[' ']) player.fire();
- updateEnemies();
- if (keys[81]) factory.newEnemy();
- println(upReleased);
- }
- void keyPressed() {
- keys[keyCode] = true;
- }
- void keyReleased() {
- keys[keyCode] = false;
- }
- void updateEnemies() {
- //if (frameCount % 120 == 0) factory.newEnemy();
- for (int i = 0; i < enemies.size(); i++) {
- Enemy e =(Enemy) enemies.get(i);
- e.update();
- if (e.destroyed) {
- enemies.remove(i);
- factory.split(e, i);
- if (enemies.size() == 0) {
- show = true;
- }
- }
- }
- }
- class Player {
- float ang, moveang, speed, x, y;
- boolean canshoot = true;
- ArrayList bullets;
- Player() {
- bullets = new ArrayList();
- ang = PI+HALF_PI;
- moveang = PI+HALF_PI;
- speed = 0;
- x = width/2;
- y = height/2;
- }
- void update() {
- if (frameCount % 45 == 0) canshoot = true;
- pushMatrix();
- translate(x, y);
- rotate(ang);
- fill(255);
- rect(-20, -7.5, 40, 15); // Center the rect
- translate(20, 0); // Translate to default Polar Coordinate 0 radians
- ellipse(0, 0, 5, 5); // Display direction
- popMatrix();
- x += cos(moveang)*speed;
- y += sin(moveang)*speed;
- if (frameCount % 5 == 0) speed = speed*9/10;
- if (speed < 0.05) speed = 0;
- if (keys[UP]) {
- speedup();
- keys[UP] = false;
- }
- if (keys[LEFT]) {
- ang -= 0.05;
- }
- if (keys[RIGHT]) {
- ang += 0.05;
- }
- if (speed == 0||(keyCode==UP)) moveang = ang;
- if (speed > 10) speed = 5;
- if (x > width+20) x = -20;
- if (x < -20) x = width+20;
- if (y > height+20) y = -20;
- if (y < -20) y = height+20;
- for (int i = 0; i < bullets.size(); i++) {
- Bullet b = (Bullet) bullets.get(i);
- b.update();
- if (b.speed < 0.05) bullets.remove(i);
- }
- }
- void fire() {
- //if (canshoot) {
- bullets.add(new Bullet(x, y, ang));
- canshoot = false;
- //}
- }
- void speedup() {
- while (speed < 5) {
- speed += 0.25;
- }
- return;
- }
- }
1