In the Processing ball game, the movements of the balls are limited

float xPos = 400;
float yPos = 300;

float xPos2 = 0;
float yPos2 = 300;

int radius = 50;

int x1, y1, x2, y2;
float theta = 0f;

int speedX = 2;
int speedY = 2;

int x1_, y1_, x2_, y2_;
float theta_ = 0f;

int speedX_ = 2;
int speedY_ = 2;

void setup()
{
  size( 800, 600 );
  background( 255 );
}

void draw()
{
  background( 255 );
  noStroke();
  fill( 255, 0, 0 );
  ellipse( xPos, yPos, radius * 2, radius * 2 );
  
  noStroke();
  fill( 255, 255, 0 );
  ellipse( xPos2, yPos2, radius * 2, radius * 2 );
  
  xPos += speedX * cos( theta );
  yPos += speedY * sin( theta );
  
  xPos2 += speedX_ * cos( -theta_ );
  yPos2 += speedY_ * sin( -theta_ );
  
  if( xPos - radius < 0 )
  {
    xPos = radius;
    speedX *= -1;
  }
  
  if( xPos + radius > width - 1 )
  {
    xPos = width - 1 - radius;
    speedX *= -1;
  }
   if( xPos + radius > width - 1 )
  {            
    xPos = width - 1 - radius;
    speedX *= -1;
  }
  
  if( yPos - radius < 0 )
  {
    yPos = radius;
    speedY *= -1;
  }
  
  if( yPos + radius > height - 1 )
  {
    yPos = height - 1 - radius;
    speedY *= -1;
  }
  
  if( xPos2 - radius < 0 )
  {
    xPos2 = radius;
    speedX_ *= -1;
  }
  
  if( xPos2 + radius > width - 1 )
  {
    xPos2 = width - 1 - radius;
    speedX_ *= -1;
  }
  
  if( yPos2 - radius < 0 )
  {
    yPos2 = radius;
    speedY_ *= -1;
  }
  
  if( yPos2 + radius > height - 1 )
  {
    yPos2 = height - 1 - radius;
    speedY_ *= -1;
  }
  
  //Collision detection
  
  int d = (int) ( sq( xPos - xPos2 ) + sq( yPos - yPos2 ) );
  
  if( d <= 4 * radius * radius )
  {
    speedX *= -1;
    speedY *= -1;
    
    speedX_ *= -1;
    speedY_ *= -1;
  }
  
  fill( 128 );
  rect( mouseX, mouseY, 200, 20 );
  
  if( xPos > mouseX && xPos < mouseX + 200 )
  {
    if( yPos + radius > mouseY )
    {
      yPos = mouseY - radius;
     
      speedY *= -1;
    }
  }
  
  if( xPos2 > mouseX && xPos2 < mouseX + 200 )
  {
    if( yPos2 + radius > mouseY )
    {
      yPos2 = mouseY - radius;
     
      speedY_ *= -1;
    }
  }
}

void mousePressed()
{
  x1 = mouseX;
  y1 = mouseY;
  
  x1_ = mouseX;
  y1_ = mouseY;
}

void mouseReleased()
{
  x2 = mouseX;
  y2 = mouseY;
  
  x2_ = mouseX;
  y2_ = mouseY;
  
  theta = atan2( y2 - y1, x2 - x1 );
  theta_ = atan2( y2_ - y1_, x2_ - x1_ );
  
  println( theta );
}

What’s your question?

What’s happening falsely,
what do you want to happen?

2 Likes