unity 3D,镜头跟随鼠标移动

一、鼠标隐藏,使用UI图片作鼠标图

二、射线在屏幕中央,用于交互

using System.Collections;
using UnityEngine;
public class ScreenPointToRay_ts : MonoBehaviour {
    Ray ray;
    RaycastHit hit;
    //记录射线到屏幕上的实际像素坐标
    Vector3 v3 = new Vector3(Screen.width / 2.0f, Screen.height / 2.0f, 0.0f);
    Vector3 hitPoint = Vector3.zero;
    // Use this for initialization
    void Start () {
    
    }
    
    // Update is called once per frame
    void Update () {
        //控制射线不断进行左右方向的扫描
        v3.x = v3.x >= Screen.width ? 0.0f : v3.x + 1.0f;
        ray = camera.ScreenPointToRay(v3);
        if(Physics.Raycast(ray,out hit,100.0f))
        {
            Debug.DrawLine(ray.origin, hit.point, Color.green);
            Debug.Log("射线探测到的物体名称: " + hit.transform.name);
        }
    }
}

三、鼠标与摄像头跟随

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

public class CameraFlow : MonoBehaviour
{
    public float moveSpeed = 5.0f;
    public GameObject FirstCamera;
    // Use this for initialization
    public bool IsClock;
    void Start()

    {
        IsClock = false;
    }

    // Update is called once per frame

    void Update()

    {

        if (IsClock)
        {

        }
        else {


            // 获得鼠标当前位置的X和Y

            float mouseX = Input.GetAxis("Mouse X") * moveSpeed;

            float mouseY = Input.GetAxis("Mouse Y") * moveSpeed;


            Cursor.visible = false;
            Cursor.lockState = CursorLockMode.Confined;
            // 鼠标在Y轴上的移动号转为摄像机的上下运动,即是绕着X轴反向旋转

            FirstCamera.transform.localRotation = FirstCamera.transform.localRotation * Quaternion.Euler(-mouseY, 0, 0);

            // 鼠标在X轴上的移动转为主角左右的移动,同时带动其子物体摄像机的左右移动

            transform.localRotation = transform.localRotation * Quaternion.Euler(0, mouseX, 0);

        }

    }

}

你可能感兴趣的:(第一人称实验,unity,3d,游戏引擎)