Unity笔记,脚本中获取物体坐标,包括世界坐标和本地坐标

简介

transform.postion 世界坐标

transform.localPosition 本地坐标(相对于父物体的坐标,Inspector(检查器)中显示的就是本地坐标)

  

 

比如,拖动父物体时,子物体在Inspector(检查器)中的坐标其实是不变的;

 

如果直接在Hierarchy中建一个物体,则打印的世界坐标和本地坐标一样;

如果先建一个空的游戏对象,然后把当前游戏物体挂到空游戏对象下,则打印出来的世界坐标和本地坐标就不一样了;

 在代码中获取世界坐标系和本地坐标系的坐标

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test1 : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        Debug.Log("123");
        
        Debug.Log("游戏物体的名称:"+ this.gameObject.name);

        Vector3 myPos = this.gameObject.transform.position;
        Debug.Log("游戏物体的世界坐标系位置:" + myPos.ToString("F3"));

        Vector3 myPosLocal = this.gameObject.transform.localPosition;
        Debug.Log("游戏物体的本地坐标系位置:" + myPosLocal.ToString("F3"));

    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

  

为简化书写,以下两种写法等效

this.gameObject.transform.position;

this.transform.position;

 

打印结果

123
UnityEngine.Debug:Log (object)
Test1:Start () (at Assets/Scripts/Test1.cs:10)

游戏物体的名称:我是立方体001
UnityEngine.Debug:Log (object)
Test1:Start () (at Assets/Scripts/Test1.cs:12)

游戏物体的位置:x=-18.4
UnityEngine.Debug:Log (object)
Test1:Start () (at Assets/Scripts/Test1.cs:15)

游戏物体的位置:(-18.400, 10.600, 42.100)
UnityEngine.Debug:Log (object)
Test1:Start () (at Assets/Scripts/Test1.cs:16)

游戏物体的世界坐标系位置:(-18.400, 10.600, 42.100)
UnityEngine.Debug:Log (object)
Test1:Start () (at Assets/Scripts/Test1.cs:19)

游戏物体的本地坐标系位置:(11.293, 8.046, 14.195)
UnityEngine.Debug:Log (object)
Test1:Start () (at Assets/Scripts/Test1.cs:22)

  

posted @ 2023-11-24 23:23  牛大胆V5  阅读(3162)  评论(0)    收藏  举报