碰撞检测之Sphere-Sphere检测
2016-03-01 23:43
507 查看
今天超级简单!
判断两个球相交不相交,直接判断两个球心的距离是否大于两个半径的和就可以了。
检测代码
public static bool IntersectSphereSphere(Sphere sphere0, Sphere sphere1)
{
Vector3 delta = sphere0.center - sphere1.center;
return delta.sqrMagnitude <= (sphere0.radius + sphere1.radius) * (sphere0.radius + sphere1.radius);
}
测试代码
public class SphereSphereTester : MonoBehaviour {
public GameObject sphere0;
public GameObject sphere1;
Sphere _sphere0;
Sphere _sphere1;
// Use this for initialization
void Start()
{
_sphere0 = new Sphere();
_sphere1 = new Sphere();
}
// Update is called once per frame
void Update()
{
UpdateShapes();
if (NIntersectTests.IntersectSphereSphere(_sphere0, _sphere1))
{
sphere0.GetComponent<MeshRenderer>().materials[0].SetColor("_Color", new Color(1, 0, 0));
} else
{
sphere0.GetComponent<MeshRenderer>().materials[0].SetColor("_Color", new Color(1, 1, 1));
}
}
void UpdateShapes()
{
_sphere0.center = sphere0.transform.position;
_sphere0.radius = 0.5f * sphere0.transform.localScale.x;
_sphere1.center = sphere1.transform.position;
_sphere1.radius = 0.5f * sphere1.transform.localScale.x;
}
}
运行结果
判断两个球相交不相交,直接判断两个球心的距离是否大于两个半径的和就可以了。
检测代码
public static bool IntersectSphereSphere(Sphere sphere0, Sphere sphere1)
{
Vector3 delta = sphere0.center - sphere1.center;
return delta.sqrMagnitude <= (sphere0.radius + sphere1.radius) * (sphere0.radius + sphere1.radius);
}
测试代码
public class SphereSphereTester : MonoBehaviour {
public GameObject sphere0;
public GameObject sphere1;
Sphere _sphere0;
Sphere _sphere1;
// Use this for initialization
void Start()
{
_sphere0 = new Sphere();
_sphere1 = new Sphere();
}
// Update is called once per frame
void Update()
{
UpdateShapes();
if (NIntersectTests.IntersectSphereSphere(_sphere0, _sphere1))
{
sphere0.GetComponent<MeshRenderer>().materials[0].SetColor("_Color", new Color(1, 0, 0));
} else
{
sphere0.GetComponent<MeshRenderer>().materials[0].SetColor("_Color", new Color(1, 1, 1));
}
}
void UpdateShapes()
{
_sphere0.center = sphere0.transform.position;
_sphere0.radius = 0.5f * sphere0.transform.localScale.x;
_sphere1.center = sphere1.transform.position;
_sphere1.radius = 0.5f * sphere1.transform.localScale.x;
}
}
运行结果
相关文章推荐
- Kinect结合Unity3D引擎开发体感游戏(一)
- Unity3D中脚本的执行顺序和编译顺序
- Unity3D动态对象优化代码分享
- javascript制作游戏开发碰撞检测的封装代码
- Unity3D获取当前键盘按键及Unity3D鼠标、键盘的基本操作
- Unity3d获取系统时间
- unity3d发布apk在android虚拟机中运行的详细步骤(unity3d导出android apk)
- Unity3D游戏引擎实现在Android中打开WebView的实例
- Android游戏开发实践之人物移动地图的平滑滚动处理
- unity3d调用手机或电脑摄像头
- Unity3d发布IOS9应用时出现中文乱码的解决方法
- 分享一个开源的网络游戏服务器架构—HouHai
- 游戏服务器端开发要点
- Unity3D插件详细评测及教学下载
- tvOS游戏开发系列(SpriteKit)之准备工作(一)
- tvOS游戏开发系列(SpriteKit)之新建tvOS游戏项目(二)
- 开源游戏 “打飞机”
- 开源游戏 “Elvish Bird”