Bullets are synchronised with player's movement - How do I stop this?
in
Programming Questions
•
2 years ago
Hi,
I am trying to get bullets to shoot in the direction the player last moved in however now, when I shoot, and then try and move again, the bullets that have been shot respond to the player moving. Run the code and you'll see!
w,a,s and d are to move up, down etc
Mouse click to shoot! :)
CODE:
//Classes
Player player;
//Arrays
ArrayList<Bullet> bullets = new ArrayList<Bullet>();
//Variables
float x = 100;
float y = 100;
float angle;
int lastPressed = millis();
void setup() {
size(200,200);
smooth();
rectMode(CENTER);
player = new Player(1);
}
void draw() {
background(255);
fill(34,56,200);
updateBullets();
player.setLocation(player.x,player.y);
player.display();
}
void updateBullets() {
ArrayList<Bullet> bulletsToDelete = new ArrayList<Bullet>();
for (Bullet b: bullets) {
b.move();
if (b.x > 200 || b.x < 0 || b.y > 200 || b.y < 0) {
bulletsToDelete.add(b);
}
b.display();
}
for (Bullet b: bulletsToDelete) {
bullets.remove(b);
}
if(millis() > 200) {
redraw();
}
}
void mousePressed() {
bullets.add(new Bullet(4,2, player.x, player.y, 2));
}
void keyPressed() {
player.move();
}
class Player {
float r;
int x,y;
PVector playerpos;
Player(float tempR) {
r = tempR;
x = 100;
y = 100;
}
void setLocation(int x, int y) {
this.x = x;
this.y = y;
}
void display() {
rectMode(CENTER);
//Vector bit
/*playerpos = new PVector(x,y);
translate(x,y);
float a = atan2(mouseY-y, mouseX-x);
rotate(a); */
//Body
fill(0);
rect(x,y,20,30);
//Head
fill(170);
rect(x,y,25,15);
}
void move() {
//if (key == CODED) {
if(key == 'w' || key == 'W') {
player.y = player.y - 6;
player.y = constrain(player.y,15,height);
} else if (key == 's' || key == 'S') {
player.y = player.y + 6;
player.y = constrain(player.y,0,height-17);
} else if (key == 'a' || key == 'A') {
player.x = player.x - 6;
player.x = constrain(player.x,3,width);
} else if (key == 'd' || key == 'D') {
player.x = player.x + 6;
player.x = constrain(player.x,0,width-17);
}
}
}
class Bullet {
float d; //Diameter of the bullet
float e; //Height of bullet
float x,y; //Location of the bullet
float speed; //Speed of bullet
float px; //Location of mouse
float py; //SAME ^^
float angle;
PVector bulletpos;
int lastPressed;
Bullet(float d, float e, float x, float y, float speed) {
this.d = d;
this.e = e;
this.x = x;
this.y = y;
this.speed = speed;
lastPressed = millis();
}
void display() {
stroke(0);
fill(142,89,19);
rect(x,y,d,e);
}
void move() {
/*bulletpos = new PVector(x,y);
translate(x,y);
float a = atan2(mouseY-y, mouseX-x);*/
if(key == 'w' || key == 'W') {
y--;
} else if(key == 's' || key == 'S') {
y++;
} else if(key == 'a' || key == 'A') {
x--;
} else if(key == 'd' || key == 'D') {
x++;
} else {
x = x;
y = y;
}
}
}
/* if(player.y > y) {
y--;
} else if(player.y < y) {
y++;
} else if(player.x > x) {
x--;
} else if(player.x < x) {
x++;
}
}
}
}*/
1