我有这段代码可以让玩家统一移动和跳跃,问题是我想让跳跃比现在慢,而不影响玩家跳跃时到达的最大 y 点,我想的是创造一个 if 语句,检查玩家 y 位置是否等于我希望他跳到的最大 y 点,然后更改一些变量以使跳跃速度变慢,我尝试这样做但它对我不起作用所以我想知道怎么做或如何以任何其他方式使跳跃变慢。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class movement : MonoBehaviour
{
public Rigidbody rb;
public float MouseSensitivity;
public float MoveSpeed;
public float JumpHeight = 40;
public float TimeToJumpApex = 2;
public float fallMultiplayer = 2.0f;
// Smoothing factors
public float moveSmoothing = 0.1f;
public float rotateSmoothing = 0.1f;
//check time of jumping
private float jumpTime;
private float landTime;
//animator
public Animator anim;
bool isJumping = false;
//player
public Transform playerTransform;
//
private Vector3 targetMoveDirection;
private Quaternion targetRotation;
// Variables for calculating jump physics
float gravity;
float jumpVelocity;
void Start()
{
//Cursor.visible = false;
}
void Update()
{
// Calculate gravity and jump velocity
gravity = -(2 * JumpHeight) / Mathf.Pow(TimeToJumpApex, 2);
jumpVelocity = Mathf.Abs(gravity) * TimeToJumpApex;
anim.SetBool("jump",false);
//vertical parameter
anim.SetFloat("vertical moving", Input.GetAxis("Vertical"));
anim.SetFloat("horizontal", Input.GetAxis("Horizontal"));
//Move
targetMoveDirection = transform.forward * Input.GetAxis("Vertical") + transform.right * Input.GetAxis("Horizontal");
rb.AddForce(targetMoveDirection * MoveSpeed, ForceMode.VelocityChange);
rb.velocity = Vector3.Lerp(rb.velocity, Vector3.zero, moveSmoothing);
//Jump
if (anim.GetCurrentAnimatorStateInfo(0).IsName("Jump"))
{
isJumping = true;
}
else
{
isJumping = false;
}
if (Input.GetKeyDown(KeyCode.Space) && Mathf.Abs(rb.velocity.y) < 0.01f && !isJumping)
{
anim.SetBool("jump",true);
rb.velocity = new Vector3(rb.velocity.x, jumpVelocity, rb.velocity.z);
jumpTime = Time.time;
}
}
private void FixedUpdate()
{
if (rb.velocity.y < 0)
{
rb.velocity += Vector3.up * gravity * fallMultiplayer * Time.deltaTime;
}
else if (rb.velocity.y > 0 && !Input.GetKey(KeyCode.Space))
{
rb.velocity += Vector3.up * gravity * fallMultiplayer * Time.deltaTime;
}
}
}
跳跃的峰值高度和到达它的时间(“慢度”)是跳跃速度和重力的函数。使用我希望可读的高中物理的一些公式,我发现了以下公式:
v0
是跳跃速度,g
是重力(绝对值),y
是跳跃的峰值高度,t
是到达峰值的时间(以秒为单位)。将所需的值代入第二个公式中的 t
和 y
,您将得到一个二次公式来求解。解决它并得到g
,重力。然后将g
和t
代入第一个公式得到跳跃高度
看起来你已经得到了正确的跳跃速度公式,但不是重力。还要记住,在你的情况下
g
代表gravity * fallMultiplayer
编辑:在您的更新中取第一行,将其替换为:
gravity = -SolveQuadraticFormula(-0.5f * TimeToJumpApex * TimeToJumpApex, TimeToJumpApex * TimeToJumpApex, -JumpHeight);
备注:
SolveQuadraticFormula
是一个函数,它采用参数 a、b、c(按此顺序)并返回方程 ax^2 + bx + c
的解。应该有 2 个解决方案,选择较小的正值(或较大的,只要确保它是正值)。你可以在网上找到大量的实现,并且自己实现并不难。