Unity(4)-坐标系统

B站学习笔记
链接:https://www.bilibili.com/video/BV12s411g7gU?p=174

在这里插入图片描述

Unity坐标系

  • World Space

  • 世界(全局)坐标系:整个场景的固定坐标,原点为世界的(0,0,0)。

  • 作用:在游戏场景中表示每个游戏对象的位置和方向。

  • Local Space

  • 物体(局部)坐标系:每个物体独立的坐标系,原点为模型轴心点,随物体移动或旋转而改变。

  • 作用:表示物体间相对位置和方向。

  • Screen Space

  • 屏幕坐标系:以像素为单位,屏幕左下角为原(0,0)点,右上角为屏幕宽、高度(Screen.width,Screen.height),Z为到相机的距离。

  • 作用:表示物体在屏幕中的位置。
    在这里插入图片描述

  • Viewport Space

  • 视口(摄像机)坐标系:屏幕左下角为原(0,0)点,右上角为(1,1),Z为到相机的距离。

  • 作用:表示物体在摄像机中的位置。
    **加粗样式**

坐标系转换

Local Space --> World Space
  • transform.forward 在世界坐标系中表示物体的正方。

  • transform.right 在世界坐标系中表示物体的正方。

  • transform.up 在世界坐标系中表示物体的正方。

  • transform.TransformPoint
    换点,受变换组件位置、旋转和缩放影响。

  • transform.TransformDirection
    转换方向,受变换组件旋转影响。

  • transform.TransformVector
    转换向量,受变换组件旋转和缩放影响。

World Space --> Local Space
  • transform.InverseTransformPoint
    换点,受变换组件位置、旋转和缩放影响。

  • transform.InverseTransformDirection
    转换方向,受变换组件旋转影响。

  • transform.InverseTransformVector
    转换向量,受变换组件旋转和缩放影响。

World Space <—>Screen Space
  • Camera.main.WorldToScreenPoint
    将点从世界坐标系转换到屏幕坐标系中

  • Camera.main.ScreenToWorldPoint
    将点从屏幕坐标系转换到世界坐标系中

练习:(1)小飞机如果超过屏幕,停止运动
(2)左出右进 右出左进

在这里插入图片描述

public class PlayerController : MonoBehaviour
{
    private Camera mainCamera;

    private void Start()
    {
        //重复使用的引用放在Start里先找一次,之后直接引用自己的引用
        mainCamera = Camera.main;
    }

    void Update()
    {
        float hor = Input.GetAxis("Horizontal");
        float ver = Input.GetAxis("Vertical");
        if (hor != 0 || ver != 0)
            Movement(hor,ver);
    }

    public float moveSpeed = 10;

    private void Movement(float hor, float ver)
    {
        hor *= moveSpeed * Time.deltaTime;
        ver *= moveSpeed * Time.deltaTime;

        //判断物体的屏幕坐标
        //世界坐标转换为屏幕坐标
        Vector3 screenPoint = mainCamera.WorldToScreenPoint(this.transform.position);
        //限制
        //(1)如果超过屏幕,停止运动
        if (screenPoint.y>=Screen.height&&ver>0 || screenPoint.y<=0&& ver<0)
        {
            ver=0;
        }
        如果到了最左边/到了最右边 还想移动 
        if (screenPoint.x >= Screen.width&&hor>0 || screenPoint.x<=0&& hor<0)
        {
            hor = 0;
        }
        //(2)左出右进 右出左进
        //上进下出 下进上出
       
        if (screenPoint.y > Screen.height)
        {
            screenPoint.y = 0;
        }
        if(screenPoint.y < 0)
        {
            screenPoint.y = Screen.height;
        }
        if (screenPoint.x > Screen.width )
        {
            screenPoint.x = 0;
        }
        if (screenPoint.x < 0)
        {
            screenPoint.x = Screen.width;
        }
        this.transform.position = mainCamera.ScreenToWorldPoint(screenPoint);
        this.transform.Translate(hor, 0, ver);
    }
}

注意:在做上进下出左进右出时需要将屏幕坐标转换为世界坐标才能实际改变物体的位置。


版权声明:本文为weixin_41963554原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。