问题
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