Unity第三人称控制器

1、挂载在摄像机上的脚本:MyCamera.cs

挂载在摄像机上

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

public class MyCamera : MonoBehaviour
{
    [Header("控制摄像机旋转的灵敏度")]
    public float mouseMoveSpeed = 2f;

    [Header("摄像机要跟随的物体")]
    public Transform playerTransfrom;

    [Header("被跟随物体与摄像机之间的距离")]
    public float direction = 5f;

    private float moveX;

    private float moveY;

    private void Update()
    {
        moveX += Input.GetAxis("Mouse X") * mouseMoveSpeed;

        moveY -= Input.GetAxis("Mouse Y") * mouseMoveSpeed;

        moveY = Mathf.Clamp(moveY, -90f, 90f);//限制旋转角度的范围,使其不超过一定的最大值和最小值

        transform.eulerAngles = new Vector3(moveY, moveX, 0);

        transform.position = playerTransfrom.position - transform.forward * direction;
    }
}

2、挂载在角色上的脚本:Player.cs

角色上的脚本

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

public class Player : MonoBehaviour
{
    public float smoothTime = 0.3f;

    public float walkSpeed = 2f;

    private float currentVelocity;

    private Transform cameraTransfrom;

    // Start is called before the first frame update
    void Start()
    {
        cameraTransfrom = Camera.main.transform;

        Cursor.lockState = CursorLockMode.Locked;  //将鼠标锁定在屏幕中心位置,鼠标的移动不再对游戏视图产生影响
    }

    // Update is called once per frame
    void Update()
    {
        Vector2 input = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));

        Vector2 inputDir = input.normalized;

        float targetRotation = Mathf.Atan2(inputDir.x, inputDir.y) * Mathf.Rad2Deg + cameraTransfrom.eulerAngles.y;

        //判断键盘是否按下
        if (inputDir != Vector2.zero)
        {
            transform.eulerAngles = Vector3.up * Mathf.SmoothDampAngle(transform.eulerAngles.y, targetRotation, ref currentVelocity, smoothTime);
            transform.Translate(transform.forward * walkSpeed * Time.deltaTime, Space.World);
        }
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值