Initializing a bool is interfering with my logic

2020-08-05 10:36发布

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;
    }

2条回答
家丑人穷心不美
2楼-- · 2020-08-05 11:00

I'd say you should not use a boolean, but an enum:

 enum Direction
 {
     Unknown,
     Left,
     Right
 }

So you can initialize it to unknown and test for that in your code.

查看更多
聊天终结者
3楼-- · 2020-08-05 11:03

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:

  1. Looking for the direction you're going to move
  2. Move the bubble
  3. Checkif the bubble has to change direction

In mi opinion, what you have to do is

  1. Check the direction to follow
  2. Move the bubble

When you start another movement, you will check the direction the bubble have to take

查看更多
登录 后发表回答