RigidBody.velocity 不为 0,即使在空闲时也是如此



不好意思,我是巴西人:p

嗯,我有一个先进的移动系统,我的球员使用RigidBody加速。使用线性拖动添加力和减速

一切都运行良好,但是当玩家空闲时,RigidBody。x轴上的速度变得疯狂,播放器在转换组件中没有移动,但我想为播放器添加动画,我无法检测到播放器是空闲还是移动,因为这。

这是困扰我很多,我搜索在其他问题,但似乎只是发生在我身上,有人可以帮助吗?下面是代码:

public class Player : MonoBehaviour
{
[Header("Components")]
public Rigidbody2D body;
public SpriteRenderer sprite;
public Animator anim;
[Header("Movement Variables")]
public float aceleration;
public float MaxSpeed = 7f;
public float linearDrag;
float move;
bool changingDirection;
[Header("Jump Variables")]
public float JumpForce;
public float airLinearDrag = 2.5f;
bool isGrounded;
[Header("Ground Check")]
public GameObject GroundCheck;
public LayerMask GroundLayer;
public float radius;
public bool DrawGizmos;
void Update()
{
Move();
LinearDrag();
if(Input.GetButtonDown("Jump") && isGrounded)
Jump();
if(move > 0 && sprite.flipX || move < 0 && !sprite.flipX)
sprite.flipX = !sprite.flipX;
}
void FixedUpdate()
{
body.AddForce(new Vector2(move * aceleration, 0f));
isGrounded = Physics2D.OverlapCircle(GroundCheck.transform.position, radius, GroundLayer);
if(Mathf.Abs(body.velocity.x) > MaxSpeed)
body.velocity = new Vector2(Mathf.Sign(body.velocity.x) * MaxSpeed, body.velocity.y);
}
void Move()
{
move = Input.GetAxisRaw("Horizontal");
if(body.velocity.x > 0 && move < 0 || body.velocity.x < 0 && move > 0)
changingDirection = true;
else
changingDirection = false;
}
void Jump()
{
body.drag = 0f;
body.AddForce(Vector2.up * JumpForce, ForceMode2D.Impulse);
}
void LinearDrag()
{
if(!isGrounded)
body.drag = airLinearDrag;
else
{
if(Mathf.Abs(move) == 0 && Mathf.Abs(body.velocity.x) > 0 && isGrounded || changingDirection && isGrounded)
body.drag = linearDrag;
else
body.drag = 0f;
}
}
void OnDrawGizmosSelected()
{
Gizmos.color = Color.white;
if(DrawGizmos)
Gizmos.DrawWireSphere(GroundCheck.transform.position, radius);
}

当你检查某项是否等于0时,你应该使用Mathf。而不是零因为计算机存储浮点数的方式。通常,计算机将零存储为一个无限小的浮点数——小到不能影响某些事情,但足以使某个值是否等于零的测试失效。

例如,您可以更改

if(Mathf.Abs(move) == 0)

if(Mathf.Abs(move) < Mathf.Epsilon)

在某些情况下,你可能需要使用一个比Mathf.Epsilon大的数。我刚刚发现我的玩家不会在某些表面上进入空闲动画的原因是他的刚体。速度。x间歇性地高于Mathf。Epsilon,让他进入一毫秒的"运行"状态,这段时间足以让闲置动画一遍又一遍地停止,直到它明显地开始工作。所以我用自己的数代替了mathf。对我来说有效的数字是0.00005f,但你必须尝试找到适合你情况的正确数字。

最新更新