You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求Unity角色移动与跳跃功能脚本(游戏开发新手求助)

Unity 角色移动与跳跃基础脚本

以下是一个基于CharacterController的基础角色控制脚本,适配新手需求,解决移动、跳跃问题,同时避免误触旋转的情况:

前置准备

  • 给你的角色对象添加CharacterController组件
  • 确保场景中的地面带有Collider组件(无需额外设置层,脚本通过内置方法直接检测地面)

完整脚本

using UnityEngine;

public class PlayerMovement : MonoBehaviour
{
    // 移动速度
    public float moveSpeed = 5f;
    // 跳跃力
    public float jumpForce = 8f;
    // 重力参数
    public float gravity = 9.81f;

    private CharacterController controller;
    private Vector3 velocity;
    private bool isGrounded;

    void Start()
    {
        controller = GetComponent<CharacterController>();
    }

    void Update()
    {
        // 检测角色是否处于地面
        isGrounded = controller.isGrounded;

        // 落地时重置垂直速度,避免重力累积导致穿模
        if (isGrounded && velocity.y < 0)
        {
            velocity.y = -2f;
        }

        // 获取键盘输入的水平/垂直轴
        float horizontal = Input.GetAxis("Horizontal");
        float vertical = Input.GetAxis("Vertical");

        // 基于角色自身方向计算移动向量,避免按键触发旋转
        Vector3 moveDir = transform.right * horizontal + transform.forward * vertical;
        controller.Move(moveDir.normalized * moveSpeed * Time.deltaTime);

        // 仅在地面时触发跳跃
        if (Input.GetButtonDown("Jump") && isGrounded)
        {
            velocity.y = Mathf.Sqrt(jumpForce * 2f * gravity);
        }

        // 应用重力
        velocity.y -= gravity * Time.deltaTime;
        controller.Move(velocity * Time.deltaTime);
    }
}

关键说明

  • 采用CharacterController替代Rigidbody,规避物理引擎带来的意外旋转问题,更适合新手上手
  • 移动逻辑绑定角色自身坐标系,仅响应方向输入,不会触发角色旋转
  • 跳跃仅在角色落地时生效,解决新手常见的"跳跃无效"问题
  • 重力处理符合基础物理逻辑,落地时重置垂直速度防止穿模

使用步骤

  1. 在Unity中新建C#脚本,命名为PlayerMovement
  2. 将上述代码复制粘贴到脚本中
  3. 将脚本挂载到你的角色对象上
  4. 在Inspector面板中调整moveSpeed、jumpForce参数适配你的游戏节奏

内容的提问来源于stack exchange,提问作者Guts

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 15:42:06