Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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();
}
share|improve this question
add comment

1 Answer

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.