类似经典fc游戏太空兔宝宝那样的摄像机一直缓慢移动直到关卡结束,而我们的主角战机需要做到不能飞出屏幕。

using UnityEngine;

public class PlayerMove : MonoBehaviour//这个脚本挂在主角战机上
{
    private Rigidbody2D rb;//刚体
    private Vector2 heading;//记录Unity输入系统的水平轴和垂直轴输入
    private void Start()
    {
        rb = gameObject.GetComponent<Rigidbody2D>();
    }
    private void FixedUpdate()
    {
        /*******************************/
        //正常的根据unity的输入系统修改刚体的速度变量,使Player移动。
        heading.x = Input.GetAxis("Horizontal");
        heading.y = Input.GetAxis("Vertical");
        rb.velocity = heading * 3.0f;
        /************************************/
        //把屏幕空间的左下坐标和右上坐标转换到世界空间,划出一个区域,利用Mathf.Clamp函数控制rb.position
        //在这块区域中,这样就可以保证主角战机走不到屏幕外面了。摄像机自带了一个屏幕空间的坐标转换到世界
        //空间的函数,这个函数的参数是三维矢量,而屏幕空间坐标是二维的,这时参数的z分量表示转换成世界空间
        //的坐标相对于摄像机的深度。这里每帧划一次区域不知道合不合适,因为太空兔宝宝是镜头缓慢向上移动的,
        //或许可以使背景缓慢向下移动,那样就不用每帧划区域了。
        var pos1 = Camera.main.ScreenToWorldPoint(new Vector3(0, 0, 10));
        var pos2 = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, 10));
        rb.position = new Vector3(Mathf.Clamp(rb.position.x, pos1.x, pos2.x), 
                        Mathf.Clamp(rb.position.y, pos1.y, pos2.y));
        /*********************************/
    }
    private void OnMouseDown()
    {
        /***************************************/
        //在这里测试了有关Screen类和Camera类的一些宽和高的变量,以及和鼠标箭头坐标做了对比,
        //没什么问题就先这样写。我对一些坐标系的变化的问题一直模模糊糊的,还有比如说OpenGL
        //和DirectX也不太熟悉,以后如果出现问题再说。
        Debug.Log("ScreenHeight:" + Screen.height);
        Debug.Log("ScreenWidth:" + Screen.width);

        Debug.Log("MousePos:" + Input.mousePosition);

        Debug.Log("CameraPixelHight:" + Camera.main.pixelHeight);
        Debug.Log("CameraPixelWidth" + Camera.main.pixelWidth);
        Debug.Log("CameraPixelRect" + Camera.main.pixelRect);
        Debug.Log("CameraScaleHight" + Camera.main.scaledPixelHeight);
        Debug.Log("CameraScaleWidth" + Camera.main.scaledPixelWidth);

        Debug.Log(Camera.main.ScreenToWorldPoint(new Vector3(0, 0, 10)));
        Debug.Log(Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, 10)));
        /***********************************************/
    }
}

借鉴了:https://blog.csdn.net/linxinfa/article/details/114540983
借鉴了:https://blog.csdn.net/StupidBoy_Q/article/details/97147678

0o0oo