简体   繁体   English

我在 Unity 2D 中正确实现跳转时遇到问题

[英]I'm having problems to implement jump properly in Unity 2D

I have written this code for my controller in Unity.我已经在 Unity 中为我的控制器编写了这段代码。 The problem is that the jump in Y axis has different height than the jump for X and Y axis simultaneously.问题是 Y 轴上的跳跃与 X 和 Y 轴同时跳跃的高度不同。

// Update is called once per frame
void FixedUpdate()
{

    Debug.Log(rigidbody.velocity);

    float inputX = Input.GetAxis("Horizontal");

    //Movement X
    if(inputX != 0 && isGrounded)
    {
        animator.SetBool("isWalking", true);
        rigidbody.velocity = new Vector2(inputX*speed, 0);

        //Turn left & right
        if(inputX > 0)
        {
            spriteRenderer.flipX = false;
        } else if (inputX < 0)
        {
            spriteRenderer.flipX = true;
        }
    } else 
    {
        animator.SetBool("isWalking", false);
    }

    //Jump
    if(Input.GetAxis("Jump") > 0 && isGrounded)
    {
        rigidbody.AddForce(Vector2.up * jumpImpulse, ForceMode2D.Impulse);
    }
}

if i understand your code right, you only gives force to X when you are in ground, so i suggest to remove isgrounded variable and use it just for jump for example in your update method如果我理解你的代码是正确的,你只会在你在地面时给 X 施加力,所以我建议删除 isgrounded 变量并将它用于跳跃,例如在你的更新方法中

if(isGround){
  if(keypress == y){
    addforce in Y
  }
}

actually im a bit oxided in unity but i hope to be usefull about logical实际上我在统一中有点氧化,但我希望对逻辑有用

I am pretty bad myself when it comes to the jumping physics, but i found these links maybe these will help you.在跳跃物理方面,我自己很糟糕,但我发现这些链接也许会对你有所帮助。

Unity 2d jumping script unity 2d 跳跃脚本

https://answers.unity.com/questions/710765/2d-c-jump-script-addforce-1.html https://answers.unity.com/questions/710765/2d-c-jump-script-addforce-1.html

I also want to know which jump is higher.我也想知道哪个跳跃更高。 You stated that there is a height difference when you jump without moving vs when you are moving.你说过不移动和移动时跳跃时存在高度差异。 Which of the two jumps higher?两者哪个跳得更高? Are you actually sure that one jumps higher than the other or does it just look like one jumps higher?你真的确定一个比另一个跳得更高还是看起来像一个跳得更高? You can test this by placing a platform an test if you can make it.如果可以的话,您可以通过对平台进行测试来进行测试。

Sorry I can't me of more help and can only speculate of what might cause the problem.抱歉,我无法提供更多帮助,只能推测可能导致问题的原因。 I would recommend however that when you do movement that you multiply it by Time.DeltaTime.但是,我建议您在进行运动时将其乘以 Time.DeltaTime。 This makes the movement time based instead of frame based.这使得移动时间基于而不是基于帧。 This will make the movement feel smoother.这将使运动感觉更流畅。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM