首页 > 解决方案 > 如何防止二维运动中的滑动

问题描述

嗨,我想移动我的角色,我环顾四周,但找不到我的代码的解决方案,当我的角色移动并且我没有按下前进按钮然后它停止但不是立即它只是在我未按下 d 按钮后立即停止这是我的代码

 using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Move : MonoBehaviour
{
    public Rigidbody2D rb2d;
    bool ismoving;
    public float speed = 5f;
    

    void FixedUpdate()
    {
        float horizontal = Input.GetAxis("Horizontal");
        if (Input.GetButton("Horizontal"))
        {
            ismoving = true;
        }
        else { ismoving = false; }

        if (ismoving)
        {
            
            rb2d.AddForce(new Vector2(horizontal, 0) * speed * Time.fixedDeltaTime *10);
        }
        else 
        { 
         while((rb2d.velocity) != (rb2d.velocity = Vector2.zero))
            {
                rb2d.AddForce(new Vector2(horizontal, 0) * Time.fixedDeltaTime *-1);                
            }        
        }
    }
}

标签: c#unity3d

解决方案


您可以将减速度的乘数更改为更大的值

while((rb2d.velocity) != (rb2d.velocity = Vector2.zero))
    {
        rb2d.AddForce(new Vector2(horizontal, 0) * Time.fixedDeltaTime * -10);                
    }  

现在它应该比以前减速 10 倍


推荐阅读