How to fix the collision bug?

Hello guys! The bouncing ball (Puck) stucks sometimes in the other ball (Player). Is there a fix for that? What did I do wrong? Thank's in advance!

Puck puck;
Player player;

void setup() {
  puck = new Puck (width/2, height/2, 2.5, 2.5, 0, 0, 60);
  size (500, 500);
}

void draw() {
  player = new Player (width/2, height/2, 75);
  background(0);
  puck.update();
  puck.display();
  player.update();
  player.display();
  player.checkCollision(puck);
}

class Player {

  int size;
  float x;
  float y;

  PVector playerPosition;
  PVector playerDirection;

  Player(float x, float y, int size) {
    this.size = size;
    this.x = x;
    this.y = y;
    playerPosition = new PVector(x, y);
    playerDirection = new PVector(mouseX-pmouseX, mouseY-pmouseY);
  }

  void display() {
    pushStyle();
    noStroke();
    fill(255, 0, 0);
    ellipse (x, y, size, size);
    popStyle();
  }

  void update() {
    x = mouseX;
    y = mouseY;


  }
  void checkCollision(Puck P) {
    if (dist(x, y, P.xpos, P.ypos) <= (size/2)+(P.size/2+1)) { //x,y == Player Position; P.x, P.y == Puck Position
      println("collision");

      P.xdirection = playerDirection.x;
      P.ydirection = playerDirection.y;

      //P.xpos = x + size/2 + P.size/2;
      //P.ypos = y + size/2 + P.size/2;
    } else {
      println(" ");
    }
  }
}

class Puck {

  int size;
  float xpos, ypos;
  float xspeed;
  float yspeed;
  float xdirection, ydirection;


  Puck(float xpos, float ypos, float xspeed, float yspeed, float xdirection, float ydirection, int size) {
    this.xpos = xpos;
    this.ypos = ypos;
    this.xspeed = xspeed;
    this.yspeed = yspeed;
    this.xdirection = xdirection;
    this.ydirection = ydirection;
    this.size = size;
  }


  void display() {
    pushStyle();
    noStroke();
    ellipse(xpos, ypos, size, size);
    popStyle();
  }

  void update() {
    xpos = xpos + (xspeed * xdirection);
    ypos = ypos + (yspeed * ydirection);

    if (xpos > width-size/2 || xpos < 0+size/2) {
      xdirection = -xdirection;
    }
    if (ypos > height-size/2 || ypos < 0+size/2) {
      ydirection = -ydirection;
    }
  }
}
Tagged:

Answers

Sign In or Register to comment.