【记录】MatrixGame思路及脚本代码

思路:

  1. 将方块的局部坐标加上相机的世界坐标,得到方块的世界坐标。
    在这里插入图片描述

  2. 将方块的世界坐标,通过主相机的WorldToScreenPoint()方法转换为屏幕坐标screenPoint。

  3. 将方块屏幕坐标与屏幕大小相减,即将screenPoint.x = Screen.width - screenPoint.x,screenPoint.y = Screen.height - screenPoint.y。因为Log打印发现,第二步得出的方块屏幕坐标是相对于屏幕右上角的,而鼠标点击获得的屏幕坐标是相对于左下角的,所以需要转换。如屏幕宽高为1920*1080,第2步得出的方块屏幕坐标为(1000, 800),通过第3步转换的结果为(1920 - 1000, 1080 - 800)。
    在这里插入图片描述

  4. 通过Vector3.Distance()求得鼠标点击坐标mousePoint和第3步方块屏幕坐标screenPoint的距离。如果距离 < 阈值,则作为点击到方块而消去方块。


代码:

  • MatrixGame.cs:其中101~123行为主要代码。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(Camera))]
public class MatrixGame : MonoBehaviour
{
    private const int ENEMY_COUNT = 20;
    private const float CAMERA_DEPTH = 0.95f;

    public class RendererInfo
    {
        public Vector3 m_Position;
        public Vector3 m_Rotation;
        public Vector3 m_Scale;
    }

    [SerializeField]
    private Mesh m_EnemyMesh = null;

    private Camera m_Camera = null;

    private Material m_EnemyMaterial = null;
    private List<Matrix4x4> m_EnemyMatrixList = new List<Matrix4x4>();
    private List<RendererInfo> m_EnemyRendererList = new List<RendererInfo>();

    private Vector3 m_CameraLeftBottom;
    private Vector3 m_CameraRightTop;

    private bool m_IsPause = false;

    private void Start()
    {
        m_Camera = GetComponent<Camera>();
        m_EnemyMaterial = new Material(Shader.Find("Universal Render Pipeline/Lit"));
        m_EnemyMaterial.enableInstancing = true;

        GameInit();
    }

    private void Update()
    {
        GameUpdate();
        GameRender();
    }

    private void OnGUI()
    {
        if (GUI.Button(new Rect(0, 0, 100, 100), m_IsPause.ToString()))
        {
            m_IsPause = !m_IsPause;
        }
    }

    private void GameInit()
    {
        Matrix4x4 projectionMatrix = CoordTranslate.PerspectiveProjectMatrix(m_Camera.fieldOfView, m_Camera.aspect, m_Camera.nearClipPlane, m_Camera.farClipPlane);
        Matrix4x4 projectionMatrixInverse = projectionMatrix.inverse;

        float depth = CAMERA_DEPTH;
        Vector4 leftBottom = new Vector4(-1, -1, depth, 1);
        Vector4 rightTop = new Vector4(1, 1, depth, 1);
        
        float A = (m_Camera.nearClipPlane + m_Camera.farClipPlane) / (m_Camera.nearClipPlane - m_Camera.farClipPlane);
        float B = 2 * m_Camera.nearClipPlane * m_Camera.farClipPlane / (m_Camera.nearClipPlane - m_Camera.farClipPlane);
        float w = B / (depth + A);
        leftBottom *= w;
        rightTop *= w;
        leftBottom = projectionMatrixInverse * leftBottom;
        rightTop = projectionMatrixInverse * rightTop;

        m_CameraLeftBottom = new Vector3(leftBottom.x, leftBottom.y, leftBottom.z);
        m_CameraRightTop = new Vector3(rightTop.x, rightTop.y, rightTop.z);
        //获取边界的其他方式

        for (int i = 0; i < ENEMY_COUNT; ++i)
        {
            RendererInfo rendererInfo = new RendererInfo();
            rendererInfo.m_Position = new Vector3(Random.Range(m_CameraLeftBottom.x, m_CameraRightTop.x),
                                                  Random.Range(m_CameraLeftBottom.y, m_CameraRightTop.y),
                                                  m_CameraLeftBottom.z);
            rendererInfo.m_Rotation = Vector3.zero;
            rendererInfo.m_Scale = new Vector3(1, 1, 1);
            m_EnemyRendererList.Add(rendererInfo);
        }
    }

    private void GameUpdate()
    {
        if (!m_IsPause)
        {
            for (int i = 0; i < m_EnemyRendererList.Count; ++i)
            {
                var rendererInfo = m_EnemyRendererList[i];
                rendererInfo.m_Rotation += new Vector3(0, 180 * Time.deltaTime, 0);
                //增加更多的运动形式
                rendererInfo.m_Rotation += new Vector3(0, 0, 180 * Time.deltaTime);
            }
        }

        if (Input.GetMouseButtonDown(0))
        {
            Vector3 mousePoint = Input.mousePosition;
            Debug.Log(mousePoint);
            //点击让对应的cube消失
            for (int i = 0; i < m_EnemyRendererList.Count; ++i)
            {
                Vector3 m_Position = new Vector3(m_EnemyRendererList[i].m_Position.x, m_EnemyRendererList[i].m_Position.y, m_EnemyRendererList[i].m_Position.z);// 注意:复制一份位置,否则会更改方块位置,导致所有方块消失
                m_Position += m_Camera.transform.position;

                Vector3 screenPoint = m_Camera.WorldToScreenPoint(m_Position);// 将立方体世界坐标转换为屏幕坐标

                screenPoint.x = Screen.width - screenPoint.x;
                screenPoint.y = Screen.height - screenPoint.y;
                Debug.Log("与屏幕坐标作用后,立方体屏幕坐标:" + "x:" + screenPoint.x + ", y:" + screenPoint.y + ", z:" + screenPoint.z);

                if ((Vector3.Distance(mousePoint, screenPoint) < 100.0))
                {
                    Debug.Log("小于临界距离");
                    m_EnemyRendererList.RemoveAt(i);// 列表中移除该方块
                }
            }
        }
    }

    private void GameRender()
    {
        PrepareRenderData(ref m_EnemyMatrixList);
        Graphics.DrawMeshInstanced(m_EnemyMesh, 0, m_EnemyMaterial, m_EnemyMatrixList);
    }

    private void PrepareRenderData(ref List<Matrix4x4> rendererList)
    {
        rendererList.Clear();
        Matrix4x4 cameraToWorldMatrix = CoordTranslate.ViewMatrix(m_Camera.transform.position, m_Camera.transform.eulerAngles).inverse;
        //Debug.Log("cameraToWorldMatrix:\n" + cameraToWorldMatrix.ToString());

        for (int i = 0; i < m_EnemyRendererList.Count; ++i)
        {
            var rendererInfo = m_EnemyRendererList[i];

            Matrix4x4 curMatrix =
                TransfromMatrix.TRS(rendererInfo.m_Position, rendererInfo.m_Rotation, rendererInfo.m_Scale);
            Matrix4x4 worldMatrix = cameraToWorldMatrix * curMatrix;

            //Debug.Log("\ncurMatrix:\n" + curMatrix.ToString());
            //Debug.Log("\nworldMatrix:\n" + worldMatrix.ToString());

            m_EnemyMatrixList.Add(worldMatrix);
        }
    }
}

其他:

[MatixGame演示视频](https://www.kdocs.cn/view/media/l/sseG9FlD9yGz
[金山文档] MatixGame演示视频.mp4)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值