如何在C#中与条件相交? [英] How to do intersection with condition in C#?

查看:99
本文介绍了如何在C#中与条件相交?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对有条件的相交或碰撞检测有疑问。我正在对一个杆(图像)和一个球(图像)之间进行碰撞检测。可以根据用户拖动栏的响应来上下移动栏。冲突检测代码如下。

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

在私有void OnUpdate(对象发送者,对象e)

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

条形图如下。

推荐答案

似乎您应该使用两个边界框描述红色的条形:顶部一个,底部一个。然后,您的代码可以检查蓝色球是否与任一个相交。在这种情况下,如果球恰好位于两个障碍之间,则它不会与任何一个相交,并且球将继续向前迈进(因此,玩家可能会死去)。

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).

顺便提一下,片段:

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

可以简单地替换为:

return !barRectangle.IsEmpty;

这篇关于如何在C#中与条件相交?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆