我在跳跃时遇到玩家移动问题



我面临的唯一问题是玩家只有在建立动力时才跳跃,我不希望我希望玩家在站立或移动时通过按空格键跳跃,我尝试了 velocity.y=jumphight 这也不起作用

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovment : MonoBehaviour
{ 
public CharacterController controller;
public float speed = 12f;
public float gravity = -9.81f;
Vector3 velocity;
public Transform groundCheck;
public float groundDistance = 0.4f;
public LayerMask groundMask;
bool isGrounded;
public float JumpHight = 3f;

void Update()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
if(isGrounded && velocity.y<0)
{
controller.slopeLimit = 45.0f;
velocity.y = -2f;//when player is grounded it just put some gravity to him all the time
}
float x = Input.GetAxis("Horizontal");//moves left and right
float z = Input.GetAxis("Vertical");//moves up and down
Vector3 move = transform.right * x + transform.forward * z;
controller.Move(move*speed*Time.deltaTime);
if(Input.GetButtonDown("Jump") && controller.isGrounded)
{

velocity.y = Mathf.Sqrt(JumpHight * -2f * gravity);
}
velocity.y += gravity * Time.deltaTime;
controller.Move(velocity * Time.deltaTime);


}
}

您可以在刚体上使用带有力模式力的加力,如果您不希望您的物理取决于 fps 使用固定更新而不是更新

GetComponent<Rigidbody>().AddForce(Vector3.up,ForceMode.Force);
Vector3 velocity;
public float gravity = -9.82f;
public float JumpHeight = 3f;
if(Input.GetButtonDown("Jump")
{
velocity.y = Matf.Sqrt(JumpHeight * -2f * gravity);
}

你也可以按照对方说的去做,这个人的代码行可能由于它有多弱而不起作用。这是所述代码的更新版本。

GetComponent<Rigidbody>().AddForce(Vector3.up * 10f ,ForceMode.Impulse);

我使用 * 的原因是增加 "up" 变量,因为它表示 Vector3(0f, 1f, 0f(; 并使用 ForceMode.Impulse 使其更不稳定、更强大。

希望这段代码对你的游戏制作有所帮助, 亲切问候。某人

最新更新