首页 > 解决方案 > Unity/C#:可控滚球的一致性

问题描述

我创建了一个可移动的 2D 球角色,但是当它停止移动时,球继续旋转一点不动,我该如何解决这个问题?

这是现有的代码:

public class Controller : MonoBehaviour
{
    public float TotalJumpForce;
    public float TotalDropForce;
    public float jumps;
    public float speed;
    public float jumpForce;
    public float dropforce;
    bool isGrounded = false;
    public Transform isGroundedChecker;
    public float checkGroundRadius;
    public LayerMask groundLayer;

    Rigidbody2D rb;

    void Start()
    {
        stalltimer = 1000;
        rb = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        TotalJumpForce = rb.velocity.y + jumpForce;
        TotalDropForce = rb.velocity.y + dropforce;
        CheckIfGrounded();
        Move();
        Jump();
        Drop();
    }
    void Move()
    {
        float x = Input.GetAxisRaw("Horizontal");
        float moveBy = x * speed;
        rb.velocity = new Vector2(moveBy, rb.velocity.y);
    }
    void Jump()
    {
        if (Input.GetKeyDown("w"))
        {
            if (jumps > 0)
                    rb.velocity = new Vector2(rb.velocity.x, TotalJumpForce);
                    jumps = jumps - 1;
        }
    }
    void Drop()
    {
        if (Input.GetKeyDown("s"))
        {

            rb.velocity = new Vector2(rb.velocity.x, TotalDropForce);
        }
    }
    void CheckIfGrounded()
    {
        Collider2D collider = Physics2D.OverlapCircle(isGroundedChecker.position, checkGroundRadius, groundLayer);
        if (collider != null)
        {
            isGrounded = true;
            jumps = 2;
            stalls = 3;
        }
        else
        {
            isGrounded = false;
        }
    }

}

改变角度和线性阻力并没有什么不同。改变重力尺度似乎也没有什么不同。

标签: c#unity3d

解决方案


rb.angularVelocity如果没有输入,您可以检查输入并重置

void Move()
{
    var x = Input.GetAxisRaw("Horizontal");
    var moveBy = x * speed;
    rb.velocity = new Vector2(moveBy, rb.velocity.y);

    if(Mathf.Approximately(move, 0f))
    {
        rb.angularVelocity = 0;
    }
}

推荐阅读