首页 > 解决方案 > 在空中跳跃时如何保持动力?

问题描述

我有一些处理跳跃和移动的代码:

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

public class FPSMovement : MonoBehaviour
{
    [SerializeField] float jumpForce;
    [SerializeField] Transform groundChecker;
    [SerializeField] float checkRadius;
    [SerializeField] LayerMask groundLayer;
    [SerializeField] float speed;
    [SerializeField] float resistance;
    [SerializeField] float sprintMultiplier = 1.5f;

    Rigidbody rb;
    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        bool IsOnGround() {
            Collider[] colliders = Physics.OverlapSphere(groundChecker.position, checkRadius, groundLayer);
            if (colliders.Length > 0) {
                return true;
            }else {
                return false;
            }
        }

        float x = Input.GetAxisRaw("Horizontal");
        float z = Input.GetAxisRaw("Vertical");

        Vector3 moveBy = transform.right * x + transform.forward * z;
        
        float actualSpeed = speed;
        
        if (Input.GetKeyDown(KeyCode.Space) && IsOnGround()) {
            rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
        }

        if (Input.GetKey(KeyCode.LeftShift)) {
            actualSpeed *= sprintMultiplier;
        }

        if (IsOnGround() == false){
            rb.MovePosition(transform.position + moveBy.normalized * actualSpeed * Time.deltaTime / resistance);
        }
        if (IsOnGround() == true){
            rb.MovePosition(transform.position + moveBy.normalized * actualSpeed * Time.deltaTime);
        }
    }
}

但是当你跳跃并且你的机智会减慢你的速度。我怎样才能做到这一点,所以当你按下 w 时你只会慢慢地加速而不是失去速度。将底部的代码涂白,它在空中的速度不同,它在空中的速度与在地面上的速度相同,这是不现实的。

标签: c#unity3d

解决方案


原始代码不支持我正在尝试执行的操作,即如果您停止按下移动键,它将停止播放器。这意味着我试图通过提供的代码来保持势头是不可能的。例子:

float x = Input.GetAxisRaw("Horizontal");
float z = Input.GetAxisRaw("Vertical");

如果你不按任何东西,这些值将为 0,所以......

rb.MovePosition(transform.position + moveBy.normalized * actualSpeed * Time.deltaTime / resistance);

由于 moveBy 值为 0,玩家将停止,因为 0 * 任何数字都是 0。

如果您希望运动与我尝试做的相同,我会推荐 Dani 的教程: https ://www.youtube.com/watch?v=XAC8U9-dTZU


推荐阅读