首页 > 解决方案 > applying velocity to rigidbody makes it float instead of dashing

问题描述

Im trying to code so that my Character dashes to the right when pressing the Left mouse button, but instead of dashing it just starts slowly glieding or lets say floating. This is the code i´ve used;

        if (Input.GetMouseButton(0))
    {
    rb.velocity = Vector2.right * DashSpeed;
    }

Im not sure but a other part of my code might be the reason for this problem but if so i would like to know how i could solve it. Thats the part im talking about

 rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);

thats the code im using for movement.

    void Start()
{
 
    cam = Camera.main;
    rb = GetComponent<Rigidbody2D>();

}
private void Update()
{

    horizontal = Input.GetAxisRaw("Horizontal");
    animator.SetFloat("Horizontal", Input.GetAxis("Horizontal"));
    if (Input.GetKeyDown(KeyCode.Space) && isGrounded == true)
    {
        float jumpVelocity = 7f;
        rb.velocity = Vector2.up * jumpVelocity;
        jumpsound.Play();
    }


    Vector3 worldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    if (Input.GetKey(KeyCode.RightAlt))
    {
        Dashing();
    }
        
 


}
void FixedUpdate()
{   
    
    

    isGrounded = Physics2D.OverlapCircle(groundCheck.position, CheckRadius, whatisGround);
    moveInput = Input.GetAxisRaw("Horizontal");
    rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);
    if (Input.GetKeyDown(KeyCode.Escape))
    {
        SceneManager.LoadScene("Main menu");
    }
    
    
}

void Dashing()
{
    rb.AddForce(Vector2.right * DashSpeed, ForceMode2D.Impulse);

}

标签: unity3dvector2drigid-bodies

解决方案


您当前代码的问题是您在几个地方直接改变了速度。一些基本的物理学,位置与时间图的积分是速度,速度的积分是加速度与时间。要获得更逼真的运动,最好将力应用于对象。这样做时,Unity 使用的物理引擎可以在给定的时间添加一个新的力,然后使用加速度可以随着时间的推移在那个方向上加速对象,然后可以随着时间的推移改变速度,这将导致位置随着时间的推移而改变。

您发布的示例代码,您直接在几个地方设置速度。

  • rb.velocity = Vector2.up * jumpVelocity;(跳)
  • rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);(移动)
  • rb.velocity = Vector2.right * DashSpeed;(短跑)

直接设置这些值时,新值会覆盖旧值。由于您的运动代码不是任何有条件的,因此它将不断写入速度,导致破折号永远不会改变任何东西,无论您是使用加力还是直接改变速度。

我会考虑让你的跳跃和冲刺都使用 AddForce,如果你喜欢直接应用速度的运动感觉,那么添加速度不要设置它。

您的上一行rb.velocity = new Vector2(moveInput * speed, rb.velocity.y);将变为rb.AddForce(new Vector2(moveInput * speed, 0), ForceMode2D.Impulse);. 同样,您可以更新您的跳跃和冲刺以匹配此。如果你得到这个工作或有更多问题,请告诉我。


推荐阅读