Player keeps moving with the bullet

I have this code, and there’s a player class and a bullet class. But when I shoot a bullet, it moves the player along with it…

class Bullet
{
  PVector pos;
  PVector vel;
  float rotation;
  
  Bullet(PVector pos, PVector tar, float rotation)
  {
    this.pos = pos;
    this.rotation = rotation;
    
    vel = new PVector(tar.x - pos.x, tar.y - pos.y);
    vel.normalize();
  }
  
  void Display()
  {
    pushMatrix();
    translate(pos.x, pos.y);
    rotate(rotation);
    fill(230, 255, 0);
    noStroke();
    rect(-15, 5, 5, 10);
    popMatrix();
    
    pos.add(vel);
  }
}

class Player
{ 
  ArrayList<Bullet> bullets;
  
  PVector pos, vel;
  boolean up, down, left, right;
  
  Player()
  {
    bullets = new ArrayList<Bullet>();
    
    pos = new PVector(60, 60);
    vel = new PVector(0, 0);
    
    up = false;
    down = false;
    left = false;
    right = false;
  }
  
  void Display()
  {
    fill(230);
    stroke(180);
    strokeWeight(3);
    ellipse(pos.x, pos.y, 40, 40);
    
    pushMatrix();
    translate(pos.x, pos.y);
    rotate(radians(degrees(atan((mouseY - pos.y) / (mouseX - pos.x))) + (mouseX > pos.x ? 270 : -270)));
    fill(120);
    noStroke();
    rectMode(CENTER);
    rect(-15, 5, 10, 35);
    popMatrix();
    
    for (int a = 0; a < bullets.size(); ++a)
      bullets.get(a).Display();
  }
  
  void Move()
  {
    if(up)
      vel.y -= 0.5;
    if(down)
      vel.y += 0.5;
    if(left)
      vel.x -= 0.5;
    if(right)
      vel.x += 0.5;

    vel.mult(0.9);
    pos.add(vel);
  }
  
  void Shoot()
  {
    bullets.add(new Bullet(pos, new PVector(mouseX, mouseY), radians(degrees(atan((mouseY - pos.y) / (mouseX - pos.x))) + (mouseX > pos.x ? 270 : -270))));
  }
}

So when I press my mouse, it calls the player.Shoot() functions, and when that happens, it move my player forward??

1 Like

I don’t understand exactly why this works (I spent half an hour tinkering around with it, confused), but the answer is pos.copy()

void Shoot()
  {
    bullets.add(new Bullet(pos.copy(), new PVector(mouseX, mouseY), radians(degrees(atan((mouseY - pos.y) / (mouseX - pos.x))) + (mouseX > pos.x ? 270 : -270))));
  }
2 Likes

huh, that works, that’s weird. I thought java was pass by reference

Java is always pass by value. That value may be a pointer to an object. One extended discussion is here:

1 Like