Unity角色或摄像机移动和旋转的控制脚本

该脚本挂载到需要被移动、旋转控制的物体身上,也可以之间挂在到摄像机上!

挂载到摄像机上可以实现第一人称视角控制!

挂载到物体身上,配合摄像机跟踪脚本可以实现,第三人称视角控制! 

第一人称视角

将角色控制脚本挂给摄像机即可!

以下是角色控制脚本:

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

public class CharacterControl : MonoBehaviour
{    
    public float MoveSpeed = 50f; //用来提供移动旋转速度
    public float RotateSpeed = 30f;

    ///


    /// 这个变量是主角Y轴旋转的角度
    ///

    private float rotationY = 0f;
    ///
    /// 这个变量是主角X轴旋转的角度
    ///

    private float rotationX = 0f;
    void Start()
    {
        //从场景中分别拿到所需的游戏物体
    }
    void LateUpdate()
    {  
        ControlRole();//用来控制物体移动和旋转
    }
   
    ///
    /// 控制主角物体移动旋转
    ///

    void ControlRole()
    {
        //控制脚本所在物体的移动;
        float X = Input.GetAxis("Horizontal");
        float Z = Input.GetAxis("Vertical");
        float Y = Input.GetAxis("Jump");
        transform.Translate(new Vector3(X * MoveSpeed * Time.deltaTime, Y * MoveSpeed * Time.deltaTime, Z * MoveSpeed * Time.deltaTime), Space.Self);
        //这个函数是获取WASD参数X,Y得到-1-1,然后赋值到三维向量作为移动函数的数值

        //接下来控制物体的旋转 当用户通过鼠标移动时,代码将根据用户的输入来旋转游戏对象。  
        float MouseXValue = Input.GetAxis("Mouse X");
        rotationY += MouseXValue * RotateSpeed * Time.deltaTime;
        //这段代码获取鼠标在水平方向上的移动值,并乘以旋转速度和时间增量。
        //然后将结果添加到 rotationY 变量中,以控制游戏对象绕 Y 轴的旋转

        float MouseYValue = Input.GetAxis("Mouse Y");
        rotationX -= MouseYValue * RotateSpeed * Time.deltaTime;
        //这段代码获取鼠标在垂直方向上的移动值,并乘以旋转速度和时间增量。
        //然后将结果减去 rotationX 变量中,以控制游戏对象绕 X 轴的旋转。

        transform.localRotation = Quaternion.Euler(rotationX, rotationY, 0f);
        //这段代码使用 Euler 角度创建一个新的旋转四元数,并将其应用于游戏对象的局部旋转。
        //通过设置 rotationX 和 rotationY 的值,可以控制游戏对象在 X 和 Y 轴上的旋转。
    }
    ///


    /// 限制一下上下旋转的角度
    ///

    void LimitRotateX()
    {

        if (rotationX < -360)
        {
            rotationX += 360;
        }
        if (rotationX > 360)
        {
            rotationX -= 360;
        }
        //限制单次旋转的最大角度,也就是不超过90度,也可以设置一个外部变量便于用户控制
        rotationX = Mathf.Clamp(rotationX, -90f, 90f);
    }
}//end class
 

第三人称

将上面, 角色控制脚本挂给模型,并添加一个摄像机追踪空物体,便于摄像机有一个追踪目标,然后把下面脚本挂给摄像机

附赠摄像机跟踪脚本(如果你角色控制脚本给了摄像机,那么这个脚本就不需要了)

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

public class CameraFollow : MonoBehaviour
{
    public Transform target; // 跟踪目标
    public float smoothTime = 0.3f; // 平滑时间

    private Vector3 velocity = Vector3.zero;

    void Update()
    {
        计算新的位置
        Vector3 targetPosition = target.TransformPoint(new Vector3(0,1,-5));//本地坐标转世界坐标
        平滑移动到新的位置
        transform.position = Vector3.SmoothDamp(transform.position, targetPosition, ref velocity, smoothTime);
        transform.LookAt(target);
    }
}

 

你可能感兴趣的:(unity,游戏引擎)