【问题标题】:Prevent player from infinite jump防止玩家无限跳跃
【发布时间】:2021-04-10 11:04:04
【问题描述】:

我有很多错误要解决。 我看到很多指南如何解决我的问题,但他们都建议我添加地面检查 已经有了,所以我不知道问题是什么。 当我希望我的玩家跳跃时,他会跳跃并且永远不会返回(他处于无限跳跃中,继续向上) 谢谢:)

代码:

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

public class PlayerManager : MonoBehaviour
{
    public float movmentSpeed;
    public float jumpForce;
   
    public Transform groundCheck;
    public LayerMask groundLayer;
   
   public bool isGrounded;
    private SpriteRenderer spriteRender;

    private Rigidbody2D rb2D;
   

    private void Start()
    {
        rb2D = GetComponent<Rigidbody2D>();
        spriteRender = GetComponent<SpriteRenderer>();
    }

    private void FixedUpdate()
    {

        PlayerMovementHandle();

        
    }

    public void PlayerMovementHandle()
    {
        GroundCheck();

        var movement = Input.GetAxis("Horizontal");
        rb2D.velocity = new Vector2(movement, rb2D.velocity.y)*movmentSpeed*Time.fixedDeltaTime;

        Flip();
        Jump();
     
    } 

    void GroundCheck()
    {
        isGrounded = false;

        Collider2D[] colliders = Physics2D.OverlapCircleAll(groundCheck.position, 0.2f, groundLayer);
        if (colliders.Length>0)
        {
            isGrounded = true;
        }
    }

    public void Jump()
    {

        if (Input.GetKeyDown(KeyCode.Space))
        {
            if (isGrounded)
            {
               // rb2D.velocity = Vector2.up * jumpForce;
                 rb2D.AddForce(new Vector2(0, jumpForce), ForceMode2D.Impulse);
    
            }

        }
    }

    public void Flip()
    {
        if (rb2D.velocity.x < -0.1f)
        {
            spriteRender.flipX = true;
        }
        else if (rb2D.velocity.x > 0.1f)
        {
            spriteRender.flipX = false;
        }
    }

  
}

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    将您的 y 值 movmentSpeed*Time.fixedDeltaTime 乘以 FixedUpdate 将使您的角色沿 y 方向移动。

    rb2D.velocity = new Vector2(movement, rb2D.velocity.y)*movmentSpeed*Time.fixedDeltaTime;
    

    尝试将 y 值设为 0,然后让 Jump() 方法进行跳转。

    rb2D.velocity = new Vector2(movement, 0f)*movmentSpeed*Time.fixedDeltaTime;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多