Unity玩家移动镜头旋转脚本

 发现CSDN上面相当一部分“移动镜头旋转”脚本不好用,我就自己发一个吧。

/// <summary>
/// 注意不要把Rigbody的静态力学打开。否则会导致功能不正常。
/// </summary>


using UnityEngine;

[RequireComponent(typeof(CharacterController))]
public class PlayerController : MonoBehaviour
{
    public static PlayerController instance;
    [SerializeField] private float moveSpeed = 5.0f;
    [SerializeField] private float mouseSensitivity = 2.0f;
    [SerializeField] private float gravity = -9.81f;

    private CharacterController characterController;
    private Transform cameraTransform;

    private float verticalRotation = 0f;
    private float verticalVelocity = 0f;

    private bool isRotating = false;
    public bool Alowmove;
    private void Awake()
    {
        Alowmove=true;
        instance = this;
    }
    void Start()
    {
        characterController = GetComponent<CharacterController>();
        cameraTransform = Camera.main.transform;
    }

    void Update()
    {
        if(Alowmove)
        {

        // Handle gravity
        if (characterController.isGrounded)
        {
            verticalVelocity = 0; // Reset on ground
        }
        else
        {
            verticalVelocity += gravity * Time.deltaTime; // Apply gravity
        }

        // Player movement
        float forwardSpeed = Input.GetAxis("Vertical") * moveSpeed;
        float sideSpeed = Input.GetAxis("Horizontal") * moveSpeed;

        Vector3 speed = new Vector3(sideSpeed, verticalVelocity, forwardSpeed);
        speed = transform.rotation * speed;
        characterController.Move(speed * Time.deltaTime);

        // Player rotation
        if (Input.GetMouseButtonDown(1)) // Rotate on right click
        {
            isRotating = true;
        }
        else if (Input.GetMouseButtonUp(1)) // Stop rotating on release
        {
            isRotating = false;
        }

        if (isRotating)
        {
            float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity;
            float mouseY = -Input.GetAxis("Mouse Y") * mouseSensitivity;

            verticalRotation += mouseY;
            verticalRotation = Mathf.Clamp(verticalRotation, -90f, 90f);

            transform.Rotate(0, mouseX, 0);
            cameraTransform.localRotation = Quaternion.Euler(verticalRotation, 0, 0);
        }
    }

    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Alvin.林

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值