Unity如何从与另一个物体发生碰撞的物体中获取位置?

Unity how to get position from objects that has collided with another object?

目前我正在尝试让一个丁字尺用我创建的线条锁定其位置,但我不确定如何获得线条的 x 位置。现在我的丁字尺能够检测到它与线条的碰撞。这是我当前的代码。

void LockPostion(float x)
{
    gObjTmp.transform.position = new Vector3 (x, this.transform.position.y, this.transform.position.z);
}

void OnCollisionEnter(Collision col)
{
    if (col.gameObject.tag == "Lines") 
    {
        Debug.Log ("Collision with line");
        LockPostion (minlockXPos);
    } 

}

就像您使用 this.transform.position 获取脚本所附加的 this 对象的位置一样,col.transform.position 应该用于获取从碰撞函数或 col.transform.position.x 仅用于 x 轴。

void OnCollisionEnter(Collision col)
{
    if (col.gameObject.tag == "Lines")
    {
        Vector3 linePos = col.transform.position;
        float linePosX = col.transform.position.x;

        Debug.Log("Collision with line");
        LockPostion(linePosX);
    }
}