繁体   English   中英

玩家不跳。 Unity RigidBody2D

[英]Player not jumping. Unity RigidBody2D

当我按下跳转键时,播放器不会跳转,但我添加的调试消息会在控制台中打印。

我的代码:

using UnityEngine;

public class PlayerController : MonoBehaviour
{
    // Start is called before the first frame update

    private Transform transform;
    private Rigidbody2D rb;

    private bool onground = false;

    public float speed;
    public float momentum;
    public float jumpForce;
    void Start()
    {
        rb = gameObject.GetComponent<Rigidbody2D>();
        transform = rb.transform;
    }

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

    private void FixedUpdate()
    {
        float moveHorizontal = Input.GetAxis("Horizontal");

        Vector3 movement = new Vector3(moveHorizontal, 0, 0);

        transform.position += movement * Time.deltaTime * speed;

        if (Input.GetButtonDown("Jump") && onground)
        {
            Jump(jumpForce);
        }
    }

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.collider.tag == "Floor")
        {
            onground = true;
            Debug.Log("Player Is On Ground!");
        }
    }

    private void OnCollisionExit2D(Collision2D collision)
    {
        if (collision.collider.tag == "Floor")
        {
            onground = false;
            Debug.Log("Player Is Not On The Ground!");
        }
    }

    private void Jump(float force)
    {
        rb.velocity = Vector2.up * force * Time.deltaTime;
        Debug.Log("Player Has Jumped!");
    }
}

玩家可以移动但不能跳跃,并且在任何地方都没有找到任何有类似问题的帖子,我可能没有足够努力地寻找或搜索正确的东西,但我找不到解决问题的方法。

首先,您通过transform组件移动玩家,但尝试通过物理( rigidbody )跳跃,这不是一个好主意,我建议您在这种情况下只使用rigidbody 此外, Time.deltaTime的乘法跳跃力没有意义,因为您从FixedUpdate()调用该方法,我假设跳跃的力量太周而无法看到结果,因此请尝试删除Time.deltaTime并增加jumpForce价值。

暂无
暂无

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

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