C# 如何解决圆碰撞问题
当我发现两个圆之间的碰撞时,我该怎么做才能防止两个圆互相穿过C# 如何解决圆碰撞问题,c#,geometry,collision,C#,Geometry,Collision,当我发现两个圆之间的碰撞时,我该怎么做才能防止两个圆互相穿过 public class CircleVsCircle { public Vector2 position { get; set; } //top left corner public float CenterX; public float CenterY; public int Width { get; set; } public int Height { get; set; } } pub
public class CircleVsCircle
{
public Vector2 position { get; set; } //top left corner
public float CenterX;
public float CenterY;
public int Width { get; set; }
public int Height { get; set; }
}
public void CircleVsCircle(CircleBody body1, CircleBody body2)
{
float radius = (body1.Radius + body2.Radius);
radius *=radius;
float distance = ((body1.CenterX - body2.CenterX) *
(body1.CenterX - body2.CenterX)) +
((body1.CenterY - body2.CenterY) *
(body1.CenterY - body2.CenterY));
if(radius > distance)
{
//solve the collision here
}
}
我假设CircleBody类已经实现了像x位置和y位置这样的属性 这是一个可能的问题
下面是我编写的一个类,它处理圆碰撞: 这是处理两个圆碰撞的代码:
public static boolean intersects(Circle circle1, Circle circle2) {
// Use Pythagorean theorem
int a = circle1.getCenterX() - circle2.getCenterX();
int b = circle1.getCenterY() - circle2.getCenterY();
float c = (float) FloatMath.sqrt((float) (Math.pow(a, 2) + Math.pow(b, 2)));
if((circle1.getRadius() + circle2.getRadius()) == c || (circle1.getRadius() + circle2.getRadius()) > c) {
return true;
}
else {
return false;
}
}
这基本上是用毕达哥拉斯求两个圆的两个中心之间的距离,并确保它小于两个圆的半径加在一起。如果小于此值,我们就知道发生了碰撞。您所说的“解决”是什么意思?这些圆有速度吗?可能是
public static boolean intersects(Circle circle1, Circle circle2) {
// Use Pythagorean theorem
int a = circle1.getCenterX() - circle2.getCenterX();
int b = circle1.getCenterY() - circle2.getCenterY();
float c = (float) FloatMath.sqrt((float) (Math.pow(a, 2) + Math.pow(b, 2)));
if((circle1.getRadius() + circle2.getRadius()) == c || (circle1.getRadius() + circle2.getRadius()) > c) {
return true;
}
else {
return false;
}
}