接触检测算法 [英] Contact Detection Algorithm
本文介绍了接触检测算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Hi
我想要一种接触检测算法来检测2球(2D)之间的碰撞。我用过这个算法,但效果不好,请帮帮我。
Hi
I want a contact detection algorithm to detect collision between 2 ball (2D). I used this algorithm but it doesn''t work well, Please Help me.
//in Ball Class:
public bool Collides(Balls otherSprite)
{
// Check if two Ball collide
if (this.rectangle.X + this.texture2D.Width > otherSprite.rectangle.X &&
this.rectangle.X < otherSprite.rectangle.X + otherSprite.texture2D.Width &&
this.rectangle.Y + this.texture2D.Height > otherSprite.rectangle.Y &&
this.rectangle.Y < otherSprite.rectangle.Y + otherSprite.texture2D.Height)
return true;
else
return false;
}
if (Balls[0].Collides(Balls[1]))
{
Vector2 tempVelocity = Balls[0].velocity;
Balls[0].velocity = Balls[1].velocity;
Balls[1].velocity = tempVelocity;
}
推荐答案
尝试使用 Rectangle.Intersect
方法 [ ^ ]。
好吧,如果你想检测两个球之间的碰撞,那么条件应该是(经谢尔盖的批准:-D)。
Well, if you want to detect collision between two balls then the condition should be (subject to Sergey''s approval :-D).
(XC0-XC1)*(XC0-XC1)+(YC0-YC1)*(YC0-YC1) <= R1*R1+R2*R2+2*R1*R2
这两个中心之间的距离小于(或等于)它们的半径之和
That is distance between the two centers is less than (or equal) to sum of their radii
我认为最好的解决方案结合了上面的两条评论,看起来应该是这样的:
I think the best solution combines both comments above, and should look something like this:
if( ! Ball1.IntersectsWith(Ball2))
{
return false;
}
double Ball1CenterX = (Ball1.Right - Ball1.Width)/2;
double Ball2CenterX = (Ball2.Right - Ball2.Width)/2;
double Ball1CenterY = (Ball1.Bottom - Ball1.Height)/2;
//double Ball2CenterY = (Ball1.Bottom - Ball1.Height)/2; // oops! (Ball1 ?) [MTH: fixed below]
double Ball2CenterY = (Ball2.Bottom - Ball2.Height)/2;
double Ball1Radious = Ball1.Width/2;
double Ball2Radious = Ball2.Width/2;
return (Ball2CenterX - Ball1CenterX)^2 + (Ball2CenterY - Ball1CenterY)^2
<=
(Ball1Radious + Ball2Radious)^2; // [MTH: fixed. don't "times 2"]
这篇关于接触检测算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文