I'm working on this method which deals with collision detection. I'm having an issue with the direction bool being initialized to true. Sometimes, when firing an object, the angle is reversed, because it's expecting the bool to be false.
If the object is initially aimed towards the left (between 0 and 350 in my code), the bool should be true. If it's aimed towards the right (between 350 and 700), the bool should be false.
How can I set the initial bool to the appropriate true/false value without interfering with subsequent collision detection?
I think the problem is when I try to check what the direction should be then set it, I'm inadvertently imposing constraints onto the objects. I can't figure out how to separate the two. Ideally, the between 0 and 350 check, and the between 350 and 700 check should only happen once, but they are being checked every time the method is called and this is causing the issue.
//Move bubble
public void MoveBubble(Bubble bubble, Vector2 distance)
{
if (bubble.stop == false)
{
velocityX = speed * distance.X;
velocityY = speed * distance.Y;
bubble.X += velocityX;
//Problem section
if (bubble.Y > 0 && bubble.Y < 350)
direction = true;
if (bubble.Y > 350 && bubble.Y < 700)
direction = false;
//End Problem section
if (direction == true)
bubble.Y += velocityY;
if (direction == false)
bubble.Y -= velocityY;
if (bubble.Y <= 0 || bubble.Y >= 350)
direction = !direction;
}
}
Fixed code:
//Move bubble and reverse it's velocity if it collides with a wall
internal void MoveBubble(Bubble bubble, Vector2 distance)
{
if (bubble.stopped == false)
if (bubble.Y < 0 || bubble.Y > 350)
bubble.velocityY = -bubble.velocityY;
bubble.Y += bubble.velocityY;
bubble.X += bubble.velocityX;
}
I'd say you should not use a boolean, but an enum:
So you can initialize it to unknown and test for that in your code.
You have to check the position of the bubble before you move it. In the position you have it at the end of the move, you might be out of the bounds of the screen.
Explaining of what I mean
What I see you're doing here is:
In mi opinion, what you have to do is
When you start another movement, you will check the direction the bubble have to take