How to do intersection with condition in C#?

有些话、适合烂在心里 提交于 2019-12-13 03:00:02

问题


I have a question about intersection or rather collision detection with condition. I am doing a collision detection between a bar(Image) and a ball(Image). The bar can be moved up and down upon user's response on dragging the bar. The collision detection codes are as below.

public bool Intersects(Rect barRectangle, Rect blueBallRectangle)
    {
        barRectangle.Intersect(blueBallRectangle);

        if (barRectangle.IsEmpty)
        {
            return false;
        }
        else
        {
            return true;
        }
    }

In private void OnUpdate(object sender, object e)

Rect blueBallRectangle= new Rect(blueBallPositionX, blueBallPositionY, blueBall.ActualWidth, blueBall.ActualHeight);
Rect barRectangle= new Rect(barPositionX, barPositionY, bar.ActualWidth, bar.ActualHeight);

For the time being, when the ball detect the collision then it will deflect away. However, I want to add on to it that it will go through the gap rather then deflecting away.

if (Intersects(barRectangle, blueBallRectangle))
        {
            this.blueBallVelocityY *= -1;
            this.blueBallVelocityX *= -1;
        }

The image of the bar is as below.


回答1:


It seems you should use two bounding boxes to describe the red bar: one on top, and one on bottom. Then your code can check to see if the blue ball intersects with either one. In this case, if the ball fits between the two barriers, it will not intersect with either one, and the ball will carry on merrily forward (whereupon the player will presumably die).

Incidentally, the snippet:

if (barRectangle.IsEmpty)
{
    return false;
}
else
{
    return true;
}

can be replaced with simply:

return !barRectangle.IsEmpty;


来源:https://stackoverflow.com/questions/17667424/how-to-do-intersection-with-condition-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!