繁体   English   中英

2D unity platformer 玩家移动问题

[英]2D unity platformer player movement question

我正在尝试制作一个向鼠标方向发射弹丸的 2D 统一平台游戏。

所以,我试图让玩家移动。 但有个问题。 它没有像我预期的那样跳跃。 当我按下跳转键时,它有时会跳转,但有时不会。 我认为跳跃在移动时通常不起作用,但我不知道如何解决这个问题。

我尝试将跳转函数放入 if 语句中,更改变量,但它仍然无法像我想象的那样工作。

我使用精灵渲染来翻转精灵,因此子对象不会在游戏进程后期与玩家一起翻转(因为当我第一次尝试通过矢量和旋转来完成时,它并没有很好地结束)

public class playerMovement : MonoBehaviour
{
    //movement variables
    public float speed;
    private float moveInput;
        
    //player components
    private Rigidbody2D rb;
    private SpriteRenderer spriteRender;
   
    //jump variables
    private float jumpInput;
    public float jumpForce;

    //ground variables

    // Start is called before the first frame update
    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
        spriteRender = GetComponent<SpriteRenderer>();
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        moving();
        jumping();
    }
    
    //move left & right function
    void moving()
    {
        moveInput = Input.GetAxis("Horizontal");
        if (moveInput > 0)
        {
            rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
            spriteRender.flipX = false;
        }
        else if (moveInput < 0)
        {
            rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
            spriteRender.flipX = true;
        }
    }

    //jump function
    void jumping()
    {
        //this input is what i tried for the jump function at the first
        //jumpInput = Input.GetAxis("Jump");
        //rb.velocity = new Vector2(rb.velocity.x, jumpInput * jumpForce);
        //but it fell down slowly so i made this line of code
        if (Input.GetButtonDown("Jump"))
        {
            rb.velocity = new Vector2(rb.velocity.x, jumpForce);
        }
    }
}

他我也犯了同样的错误。 你只需要在“Update()”中加入“jumping()”!

因为如果它在 Fixedupdate 中,它将只允许您每秒跳跃或类似的东西。

https://docs.unity3d.com/ScriptReference/Rigidbody2D.AddForce.html或者,您可以使用 rb.AddForce 使角色跳跃。

暂无
暂无

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

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