Unity3d相机跟随角色

摄像机跟随目标,鼠标滑轮可以调整距离

InputController.cs

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

public class InputController : MonoBehaviour
{
    public Vector2 m_Movement;
    public bool isAtk;
    public Vector3 m_Camera;

    // Update is called once per frame
    void Update()
    {
        m_Movement.Set(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
        isAtk = Input.GetMouseButtonDown(0); // Input.GetButtonDown("Fire1");
        m_Camera.Set(Input.GetAxis("Mouse X"),Input.GetAxis("Mouse Y"),Input.GetAxis("Mouse ScrollWheel"));
    }
}

ArpgCameraC.cs

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

public class ArpgCameraC : MonoBehaviour
{
    public InputController inputc;
    public Transform target;

    float xSpeed = 250;
    float ySpeed = 125;

    float x = 0;
    float y = 0;

    float distance = 4;
    float zoomRate = 80;
    float yMinLimit = -10;
    float yMaxLimit = 70;
    float disMinLimit = 2;
    float disMaxLimit = 10;

    Vector3 offset = new Vector3(0,1);
    Vector3 rotateOffset = new Vector3(0.1f, 0, -1);

    // Start is called before the first frame update
    void Start()
    {
        // 锁定鼠标
        Cursor.lockState = CursorLockMode.Locked;
    }

    // Update is called once per frame
    void Update()
    {
        // 镜头角度
        x += inputc.m_Camera.x * xSpeed * Time.deltaTime;
        y -= inputc.m_Camera.y * ySpeed * Time.deltaTime;
        y = ClampAngle(y, yMinLimit, yMaxLimit);

        Quaternion rotation = Quaternion.Euler(y, x, 0);
        transform.rotation = rotation;

        // 只要移动,镜头始终朝着角色前方
        if (inputc.m_Movement.x != 0 || inputc.m_Movement.y != 0)
        {
            // 目标跟随视角旋转
            target.transform.rotation = Quaternion.Euler(0,x,0);
        }

        // 鼠标滚动 镜头距离
        distance -= (inputc.m_Camera.z * Time.deltaTime) * zoomRate * Mathf.Abs(distance);
        distance = Mathf.Clamp(distance,disMinLimit,disMaxLimit);

        transform.position = target.position + offset + rotation * (rotateOffset * distance);
    }

    float ClampAngle(float angle,float min,float max)
    {
        if (angle > 360)
        {
            angle -= 360;
        } else if (angle < -360)
        {
            angle += 360;
        }
        return Mathf.Clamp(angle, min, max);
    }
}

Unity3d相机跟随角色

上一篇:Python-Turtle库(海龟绘图)基础知识点


下一篇:canvas_03 画弧线