20240112-【UNITY 学习】实现第一人称移动教程

本文介绍了如何在Unity中创建对象,挂载Rigidbody、相机脚本和角色移动脚本,实现角色朝向控制、摄像机跟随以及基本的跳跃功能。
摘要由CSDN通过智能技术生成

1、创建一个空物体,挂载Rigidbody组件,并设置相应参数

在这里插入图片描述

2、在上述空物体下创建一个胶囊体,两个空物体,一个用来控制朝向,另一个用来控制摄像机

在这里插入图片描述

3、给摄像机创建一个父物体,并挂载脚本MoveCamera_01.cs

在这里插入图片描述

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

public class MoveCamera_01 : MonoBehaviour
{
    public Transform cameraPosition;
    private void Update()
    {
        transform.position = cameraPosition.position;
    }
}

4、给摄像机挂载脚本PlayerCam_01.cs

在这里插入图片描述

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

public class PlayerCam_01 : MonoBehaviour
{
    // 视觉灵敏度参数
    public float sensX = 400;
    public float sensY = 400;

    // 视角垂直旋转角度限制
    public float minAngle = -90f;
    public float maxAngle = 90f;

    // 角色朝向的 Transform,用于水平旋转
    public Transform orientation;

    // 当前的 X 和 Y 旋转角度
    private float xRotation;
    private float yRotation;

    private void Start()
    {
        // 初始时锁定鼠标光标并隐藏光标
        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;
    }

    private void Update()
    {
        // 获取鼠标输入
        float mouseX = Input.GetAxisRaw("Mouse X") * Time.deltaTime * sensX;
        float mouseY = Input.GetAxisRaw("Mouse Y") * Time.deltaTime * sensY;

        // 更新水平旋转角度
        yRotation += mouseX;

        // 更新垂直旋转角度,并限制在指定范围内
        xRotation -= mouseY;
        xRotation = Mathf.Clamp(xRotation, minAngle, maxAngle);

        // 应用旋转到摄像机的 Transform 上,实现视角旋转
        transform.rotation = Quaternion.Euler(xRotation, yRotation, 0);

        // 应用水平旋转到角色的 Transform 上,使角色朝向与摄像机一致
        orientation.rotation = Quaternion.Euler(0, yRotation, 0);
    }
}

5、给主角挂载脚本PlayerMovement_01.cs

在这里插入图片描述

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

public class PlayerMovement_01 : MonoBehaviour
{
    public float moveSpeed = 7; // 玩家移动速度

    public float groundDrag = 5; // 地面时的阻力

    public float playerHeight = 2; // 玩家身高
    public LayerMask whatIsGround; // 地面的LayerMask
    private bool grounded; // 是否在地面上

    public float jumpForce = 6; // 跳跃力度
    public float jumpCooldown = 0.25f; // 跳跃冷却时间
    public float airMultiplier = 0.4f; // 空中移动速度衰减
    private bool readyToJump = true; // 是否可以跳跃

    public KeyCode jumpKey = KeyCode.Space; // 跳跃键

    public Transform orientation; // 玩家朝向的Transform

    private float h; // 水平输入
    private float v; // 垂直输入

    private Vector3 moveDirection; // 移动方向

    private Rigidbody rb; // 玩家刚体

    private void Start()
    {
        rb = GetComponent<Rigidbody>();
        rb.freezeRotation = true; // 防止刚体旋转
    }

    private void Update()
    {
        grounded = Physics.Raycast(transform.position, Vector3.down, playerHeight * 0.5f + 0.2f, whatIsGround);

        MyInput();

        SpeedControl();

        if (grounded)
            rb.drag = groundDrag;
        else
            rb.drag = 0;
    }

    private void FixedUpdate()
    {
        MovePlayer();
    }

    private void MyInput()
    {
        h = Input.GetAxisRaw("Horizontal");
        v = Input.GetAxisRaw("Vertical");

        if (Input.GetKey(jumpKey) && readyToJump && grounded)
        {
            readyToJump = false;

            Jump();

            Invoke(nameof(ResetJump), jumpCooldown);
        }
    }

    private void MovePlayer()
    {
        // 根据朝向计算移动方向
        moveDirection = orientation.forward * v + orientation.right * h;

        if (grounded)
        {
            rb.AddForce(moveDirection.normalized * moveSpeed * 10f, ForceMode.Force);
        }
        else if (!grounded)
        {
            rb.AddForce(moveDirection.normalized * moveSpeed * 10f * airMultiplier, ForceMode.Force);
        }
    }

    private void SpeedControl()
    {
        Vector3 flatVel = new Vector3(rb.velocity.x, 0f, rb.velocity.z);

        if (flatVel.magnitude > moveSpeed)
        {
            // 限制速度在设定范围内
            Vector3 limitedVel = flatVel.normalized * moveSpeed;

            rb.velocity = new Vector3(limitedVel.x, rb.velocity.y, limitedVel.z);
        }
    }

    private void Jump()
    {
        //rb.velocity = new Vector3(rb.velocity.x, 0f, rb.velocity.z);
        rb.velocity = Vector3.zero;

        // 添加向上的力以实现跳跃
        rb.AddForce(transform.up * jumpForce, ForceMode.Impulse);
    }

    private void ResetJump()
    {
        readyToJump = true;
    }
}
  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您好!基于Unity引擎实现第一人称移动需要以下步骤: 1. 创建一个新的Unity项目,并在场景中添加一个空对象作为主摄像机。 2. 创建一个新的C#脚本文件,并将其添加到主摄像机上。 3. 在脚本中使用Input.GetAxis函数获取玩家输入的水平和垂直轴向的值。 4. 使用CharacterController组件的Move函数来移动主摄像机,该函数需要一个Vector3类型的参数来表示移动的方向和速度。 5. 在Update函数中调用Move函数,并传入计算后的移动向量。 6. 使用Cursor.lockState属性和Cursor.visible属性来控制鼠标显示和锁定状态,以实现第一人称视角。 下面是一个示例代码: ``` using UnityEngine; public class FirstPersonMovement : MonoBehaviour { public float speed = 6.0f; public float jumpSpeed = 8.0f; public float gravity = 20.0f; private Vector3 moveDirection = Vector3.zero; private CharacterController controller; void Start() { controller = GetComponent<CharacterController>(); } void Update() { float horizontal = Input.GetAxis("Horizontal"); float vertical = Input.GetAxis("Vertical"); if (controller.isGrounded) { moveDirection = new Vector3(horizontal, 0, vertical); moveDirection = transform.TransformDirection(moveDirection); moveDirection *= speed; if (Input.GetButton("Jump")) { moveDirection.y = jumpSpeed; } } moveDirection.y -= gravity * Time.deltaTime; controller.Move(moveDirection * Time.deltaTime); Cursor.lockState = CursorLockMode.Locked; Cursor.visible = false; } } ``` 希望可以帮到您!

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值