您的位置:首页 > 移动开发 > Unity3D

Unity3D多物体碰撞关键代码

2016-09-21 17:08 260 查看
void Update () {

for(int i=0; i<images.Length-1; i++)
{
Image img0 = images[i];
for(int j=i+1; j<images.Length; j++)
{
Image img1 = images[j];
float dx = img1.GetComponent<RectTransform>().position.x – img0.GetComponent<RectTransform>().position.x;
float dy = img1.GetComponent<RectTransform>().position.y – img0.GetComponent<RectTransform>().position.y;
float dist = Mathf.Sqrt(dx * dx + dy * dy);
float minDist = img0.GetComponent<RectTransform>().rect.width / 2 + img1.GetComponent<RectTransform>().rect.width/2;
if (dist < minDist)
{
float angle = Mathf.Atan2(dy, dx);
float tx = img0.GetComponent<RectTransform>().position.x + dx / dist * minDist;
float ty = img0.GetComponent<RectTransform>().position.y + dy / dist * minDist;
float ax = (tx – img1.GetComponent<RectTransform>().position.x) * 0.05f;
float ay = (ty – img1.GetComponent<RectTransform>().position.y) * 0.05f;
img0.GetComponent<Player>().speedX -= ax;
img0.GetComponent<Player>().speedY -= ay;
img1.GetComponent<Player>().speedX += ax;
img1.GetComponent<Player>().speedY += ay;
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  unity3d 多物体碰撞