首页 > 解决方案 > Unity 在跌落时检测碰撞

问题描述

我正在尝试制作一个拖放系统,我正在拖动的对象在拖放到它们上时会粘在某个位置,否则会自动返回到原始位置。

public Vector3 dist;
public Vector3 startPos;
public float posX;
public float posY;
public GameObject TopLeftUnfilled;
public GameObject TopRightUnfilled;
public GameObject BottomleftUnfilled;
public GameObject BottomRightUnfilled;
public int count1;
public int count2; 
public int count3;
public int count4;
public bool collided = false;

void Awake()
{
    startPos = gameObject.transform.localPosition;  
}

void OnMouseDown(){
    dist = Camera.main.WorldToScreenPoint(transform.position);
    posX = Input.mousePosition.x - dist.x;
    posY = Input.mousePosition.y - dist.y;

}

void OnMouseDrag(){
    Vector3 curPos = 
        new Vector3(Input.mousePosition.x - posX, 
            Input.mousePosition.y - posY, dist.z);  

    Vector3 worldPos = Camera.main.ScreenToWorldPoint(curPos);
    transform.position = worldPos;
}

void OnMouseUp()
{
    if (collided)
    {
        foreach (Transform childTopLeft in TopLeftUnfilled.transform) 
        {
            count1++;
            if (count1 == 4) 
            {
                gameObject.transform.localPosition = new Vector3 (-2.3f, 1.195f, 0f);
            } 
            else
            {
                gameObject.transform.localPosition = startPos;
            }
        }
    }
}

void OnTriggerEnter(Collider other)
{
    if (other.gameObject.tag == "TileUnfilled") 
    {
        Debug.Log ("collision");
        collided = true;
    }
}

void OnCollisionExit(Collision collision)
{
    collided = false;
}

截屏

我现在只用左上角的未填充区域对此进行测试,但没有检测到碰撞。我应该怎么办?

标签: c#unity3d

解决方案


我面前没有要测试的 Unity,但我很确定

void OnTriggerEnter(Collider other)

应该

void OnCollisionEnter(Collider other)

推荐阅读