Unity3D 摄像机跟随鼠标旋转

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

public class Test : MonoBehaviour
{

    Vector3 oldMousePosition;
    Vector3 newMousePosition;

    // Use this for initialization
    void Start()
    {
        oldMousePosition = Input.mousePosition;
        newMousePosition = Input.mousePosition;
    }

    // Update is called once per frame
    void Update()
    {
        newMousePosition = Input.mousePosition;
        if (newMousePosition != oldMousePosition)
        {
            transform.Rotate(Vector3.up, newMousePosition.x - oldMousePosition.x);
            transform.Rotate(Vector3.right, -1 * (newMousePosition.y - oldMousePosition.y));
            transform.eulerAngles = new Vector3(transform.eulerAngles.x, transform.eulerAngles.y, 0);
        }
        oldMousePosition = Input.mousePosition;
    }
}

 

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

public class MoveFollowMouse : MonoBehaviour
{
    GameObject cube;
    Ray ray;

    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        RaycastHit hit;
        if (Input.GetMouseButtonDown(0))
        {
            ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out hit))
            {
                if (hit.transform.tag == "Player")
                {
                    cube = hit.transform.gameObject;
                }
            }
        }
        if (Input.GetMouseButtonUp(0))
        {
            cube = null;
        }
        if (cube != null)
        {
            ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            cube.transform.position = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, cube.transform.position.z - Camera.main.transform.position.z));
        }
    }
}

 

Screen.width:屏幕分辨率的宽

Screen.height:屏幕分辨率的高

你可能感兴趣的:(Unity3D 摄像机跟随鼠标旋转)