c# - Rigidbody2D 中的 AddForce 根本不起作用

标签 c# unity3d 2d

我一直在跟随指南,我一直在几十个论坛中跋涉,随后,我一直在撕掉我剩下的头发!

正如您在代码中看到的,我正在尝试使用速度进行移动,并使用 AddForce 进行跳跃 Action 。如果我使用速度,它会跳得超快并且达到最大值,我只是不希望这种情况发生。我想要一个平滑的跳跃,更真实,所以我看到它说用 AddForce 代替。除了……它甚至根本不起作用,他现在就是不跳……什么都没有。

我以速度工作。代码是 rb.velocity = jumping * jumpForce;

就像我说的,这很有效,但它跳得快得离谱,而且看起来一点也不正确。

public class PlayerController : MonoBehaviour
{

    public float speed = 3.0f;
    public float jumpForce = 4.0f;
    public Rigidbody2D rb;
    public Vector2 movement;
    public bool isJumping;
    public Animator animate;
    public Vector2 jumping = new Vector2(0,1);


    // Start is called before the first frame update
    void Start()
    {
        rb = this.GetComponent<Rigidbody2D>();
        //animate = this.GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        //animate.SetFloat("Horizontal", Input.GetAxis("Horizontal"));

        movement = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));


    }
    void FixedUpdate()
    {

        moveCharacter(movement);
        jumpCharacter();


    }

    void moveCharacter(Vector2 direction)
    {
        rb.velocity = direction * speed;

    }

    void jumpCharacter()
    {
        if(Input.GetKey(KeyCode.Space) && !isJumping)
        {
            isJumping = true;

            rb.AddForce(jumping * jumpForce);
        }
    }

    void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("Ground"))
        {
            isJumping = false;
            rb.velocity = Vector2.zero;
        }
    }

}

最佳答案

我遇到过和你一样的情况,我发现使用

  • Rigidbody2D.velocity =+ Vector2.up * force;FixedUpdate()
  • 代替 Rigidbody2D.AddForce(Vector2.up * force); 可以工作。

但是我也想知道为什么AddForce不能正常工作。

关于c# - Rigidbody2D 中的 AddForce 根本不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55879622/

相关文章:

c# - 安装插件时 NopCommerce 4.10 错误

c# - LINQ 连接来自不同类的值

c - 在 C 中反转二维数组

c# - NHibernate : No update with composite key

c# - 如何在代码中动态地将新的视觉状态添加到自定义控件模板?

c# - Unity Ads UnityEngine.Advertisements 库无法访问

c# - 音乐的音调检测

image - Unity UI以编程方式添加图像

c# - 使用 viewmatrix 移动二维对象

c - 使用开罗在 gtkentry 上方绘图