如何使触发的对象在与另一个对象碰撞时停止移动



我在拖动一个游戏对象时遇到了问题,由于我需要制作一些函数,它的长方体碰撞器被触发。问题是,我不知道如何阻止这个游戏对象移动到与碰撞的另一个游戏对象之外。

//This is my object drag, might help.. it's a .cs code attached to the game object
void OnMouseDrag()
{
    Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
    Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
    if (Global.noGrid[0]) //noGrid means inside the grid ('no' in Portuguese means 'in')
    {
        transform.position = Global.FindClosestObject(curPosition, "gizmo_peca").transform.position; // here i find the game closest gameobject inside the grid, i do that because i need a snap (that's why i need the trigger working to, to recognize which gameobject it's colliding
    }
    else
    {
        transform.position = new Vector3(curPosition.x, curPosition.y, curPosition.z);
    }
}
// This is what i tried but with no success in BlockForma.cs (It's how I call my gameobject above)
void OnTriggerEnter2D(Collider2D c)
{
    if (c.tag == "Forma")
    {
        c.rigidbody2D.velocity = new Vector2(0,0);
        Debug.Log("Hello");
    }
}

该解决方案经过测试,100%有效。

如果你想停止游戏对象,

rigidbody2D.velocity = Vector2.zero; 

如果你想停止碰撞物体,那么

col.rigidbody2D.velocity = Vector2.zero;

最新更新