Simple collision game. the ellipse strange moves

hi. i want to create simple game where i have ellipse moving randomly and line at the bottom of the screen and its move along mouse X axis to void the ellipse from touch the bottom screen end. but bellow code cause the ellipse moves strange

/**
 * Bounce. 
 * 
 * When the ellipse hits the edge of the line, it reverses 
 its direction and when the ellipse hit the bottom edge it will start over. 
 */
 
int rad = 30;        // Width of the shape
float xpos, ypos;    // Starting position of shape    

float xspeed = 4.8;  // Speed of the shape
float yspeed = 3.2;  // Speed of the shape

int xdirection = 1;  // Left or Right
int ydirection = 1;  // Top to Bottom


void setup() 
{
  size(480, 720);
  noStroke();
  frameRate(30);
  ellipseMode(RADIUS);
  // Set the starting position of the shape
  xpos = width/2;
  ypos = height/2;
}

void draw() 
{
  background(102);
  
  // Update the position of the shape
  xpos = xpos + ( xspeed * xdirection );
  ypos = ypos + ( yspeed * ydirection );
  
  // Test to see if the shape exceeds the boundaries of the screen
  // If it does, reverse its direction by multiplying by -1
  if (xpos > width-rad || xpos < rad) {
    xdirection *= -1;
  }
  if (ypos > height-rad || ypos < rad) {
    ydirection *= -1;
  }

 

  // Draw the shape
  ellipse(xpos, ypos, rad, rad);
  stroke(255);
  line(mouseX,700,mouseX + 50, 700);
  float disT = dist(mouseX,700,xpos, ypos );
    if (disT < 35) {
    xdirection *= -1;
  }
  
}

thankyou for any help

The problem is caused in this code.

The draw method is executed approximatey 60 times a second so there might be several continuous frames when disT < 35 and in each of these frames the xdirection is reversed so the ellipse jiggles.

There is no simple fix for this code, a more sophisticated algorithm is required. I suggest you research collision detection techniques / algorithms.

2 Likes