Unity C#跳跃协程创建浮动跳跃

时间:2019-12-11 19:23:46

标签: c# unity3d 2d coroutine

我正在尝试统一实现变量跳转,并从几年前找到了本教程,其中最后一个(称为“ The Just Right”)看起来像我想要的精确跳转(我正在不断地尝试跑步者)。

不幸的是,由于只显示了部分代码,而且由于它很旧,所以没人能在注释中回答。

我知道了jumpButtonPressed和jumpTime是什么,但是我对jumpVector可能意味着什么感到困惑。

我现在可以进行跳转了,但是似乎比示例看起来要浮动得多,所以我认为我没有正确地替换jumpVector。

这是本教程的来源:https://www.gamasutra.com/blogs/DanielFineberg/20150825/244650/Designing_a_Jump_in_Unity.php

到目前为止,这就是我要解决的问题,跳转协程与本教程中的协程基本相同,除了我拥有Vector2.up + new Vector2(0,jumpDist)而不是jumpVector。我似乎永远也感觉不到跳跃,任何建议都会很好。

public class PlayerController : MonoBehaviour {

    [SerializeField]
    private float speed = 3.0f;
    [SerializeField]
    private float jumpDist = 20.0f;
    [SerializeField]
    private float airTime = 0.5f;

    private Rigidbody2D rigidbody;
    private bool jumping = false;
    private bool jumpBtnDown = false;

    private void Start() {
        rigidbody = GetComponent<Rigidbody2D>();
    }

    private void Update() {
        //when space clicked, sets jumping and jumpBtnDown to true, starts jump coroutine
        if(Input.GetKeyDown(KeyCode.Space) && jumping == false) {
            Debug.Log("jump button pressed");
            //rigidbody.AddForce(Vector2.up * jumpDist);
            jumping = true;
            jumpBtnDown = true;
            StartCoroutine(jump());
        }

        //if space let go, sets jumpBtnDown to false so the jump coroutine can end early
        if(Input.GetKeyUp(KeyCode.Space)) {
            Debug.Log("jump button released");
            jumpBtnDown = false;
        }

    }

    private void FixedUpdate() {
        //basic movement for testing
        float move = Input.GetAxisRaw("Horizontal");

        rigidbody.velocity = new Vector2(speed * move, rigidbody.velocity.y);
    }

    IEnumerator jump() {
        Debug.Log("jump coroutine started");
        rigidbody.velocity = Vector2.zero;
        float timer = 0;

        while(jumpBtnDown == true && timer < airTime) {
            float percentJumpCompleted = timer / airTime;

            //this is the line that I don't think is working right and causing the jump to be floaty
            Vector2 jumpVectorThisFrame = Vector2.Lerp((Vector2.up + new Vector2(0, jumpDist)), Vector2.zero, percentJumpCompleted);
            rigidbody.AddForce(jumpVectorThisFrame);
            timer += Time.deltaTime;
            yield return null;
        }

        jumping = false;
        Debug.Log("jump coroutine ended");
    }
}

(我尚未测试播放器是否已接地,因此该代码当前允许永久跳,但我计划在跳变正常后再添加一次)

0 个答案:

没有答案
相关问题