Unity 3D的玩家移动可以正常工作,但跳跃键的绑定不起作用
我对Unity还很新,正在尝试做一个可以移动、跳跃等的角色。
然而,跳跃似乎还有些问题。玩家的移动和看向(环顾四周)都能正常进行,但跳跃机制似乎出问题。我在使用Unity 6,并已启用“both” Active Input Handling风格。我已经勾选了“Jump”并且有“isGrounded”的检查,但玩家仍然跳不起来。将不胜感激。请参阅下面的代码以作参考:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public CharacterController controller;
public float speed = 12f;
public float gravity = -9.81f * 2;
public float jumpHeight = 3f;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
Vector3 velocity;
bool isGrounded;
// Update is called once per frame
void Update()
{
//check if space key is pressed down
if (Input.GetButtonDown("Jump"))
{
GetComponent<Rigidbody>().AddForce(Vector3.up * 5, ForceMode.VelocityChange);
}
//checking if we hit the ground to reset our falling velocity, otherwise player will fall faster the next time
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if (isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
//right is the red Axis, foward is the blue axis
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move * speed * Time.deltaTime);
//check if the player is on the ground so he can jump
if (Input.GetButtonDown("Jump") && isGrounded)
{
//the equation for jumping
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);
}
}
解决方案
主问题在于你在同一个脚本中混用了 CharacterController 和 Rigidbody。
CharacterController 不使用Unity的物理系统,因此对一个 Rigidbody 调用 AddForce 在这里实际上不会起作用。这就是跳跃不起作用的原因。
现在你还存在两种不同的跳跃方法:
- 一种使用 Rigidbody.AddForce()
- 另一种使用带有 CharacterController 的velocity
它们不能一起工作,可能导致行为不一致。
既然你已经在移动中使用 CharacterController,最简单的修复方法是坚持使用它,并移除 Rigidbody 的跳跃代码:
if (Input.GetButtonDown("Jump"))
{
GetComponent<Rigidbody>().AddForce(Vector3.up * 5, ForceMode.VelocityChange);
}
然后继续保留你对跳跃的 CharacterController 逻辑:
if (Input.GetButtonDown("Jump") && isGrounded)
{
velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
}
这样所有内容都在同一个系统中得到一致处理。
另外,请再次确认地面检测是否正常工作,因为跳跃取决于 isGrounded 为true。
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。