0
\$\begingroup\$

I have a edge collision problem with a simple game that i am developing. Its about throwing a coin across the screen. I am using the code below to detect edge collisions so i can make the coin bounce from the edges of the screen.

Everything works as i want except one case. When the coin hits left edge and goes to right edge the system doesnt detect the collision. The rest cases are working perfectly, like hitting the right edge first and then the left edge.

Can someone suggest a solution for it?

public void onMove(float dx, float dy) {
 coinX += dx;
 coinY += dy;

  if (coinX > rightBorder) {
    coinX = ((rightBorder - coinX) / 3) + rightBorder;
  }
  if (coinX < leftBorder) {
    coinX = -(coinX) / 3;
  }
  if (coinY > bottomBorder) {
    coinY = ((bottomBorder - coinY) / 3) + bottomBorder;    
  }

  invalidate();
}
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Your code should look something like this assuming you are movin from the center of the object.

onMove(...)
{
//check collision against right wall. to get the center, take the position and add the half of width. if that is bigger than our rightscreen edge. lets assume it´s 800.

float rightScreenEdge = 800.0f;
if( coinX + ( Width / 2 ) > rightScreenEdge )
{
//lets take the velocity and negate it to make it move the otherway.
    velocity.x = -velocity.x;
}
//lets check against the left corner, which is actualy 0 in screenspace.
else if( coinX - ( Width / 2 ) < 0 )
{
    velocity.x = -velocity.x;
}

coinX += velocity.x;
}

i hope this gives you the idea how it works.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .