Answer the question
In order to leave comments, you need to log in
Unity2d character velocity keeps changing, why?
The character's RigidBody2D velocity.y changes from -3.949388e-09 to 3.949388e-09. Even when he's on the ground, I don't understand why. Removed Run() from FixedUpdate, everything became normal, only after the character lands it changes a couple of times, and goes back to 0. Code attached:
using UnityEngine;
using System.Collections;
public class CharacterControllerScript : MonoBehaviour
{
public float maxSpeed = 10f;
public float maxJump = 50f;
private bool isFacingRight = true;
[SerializeField]
private bool isGrounded;
private Animator anim;
private Rigidbody2D characterRigidBody;
private void Start()
{
characterRigidBody = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
}
private void FixedUpdate()
{
Run();
Jump();
CharacterFlyOrFall();
}
private void Run()
{
float move = Input.GetAxis("Horizontal");
anim.SetFloat("xSpeed", Mathf.Abs(1));
characterRigidBody.velocity = new Vector2(move * maxSpeed, characterRigidBody.velocity.y);
if (move > 0 && !isFacingRight)
FlipCharacter();
else if (move < 0 && isFacingRight)
FlipCharacter();
}
private void CharacterFlyOrFall()
{
if (!isGrounded)
{
anim.SetFloat("ySpeed", characterRigidBody.velocity.y);
}
else
{
anim.SetFloat("ySpeed", Mathf.Abs(0));
}
}
private void Jump()
{
if (isGrounded && Input.GetKey(KeyCode.UpArrow))
{
characterRigidBody.AddForce(new Vector2(0,maxJump));
isGrounded = false;
}
}
private void FlipCharacter()
{
isFacingRight = !isFacingRight;
Vector3 theScale = transform.localScale;
theScale.x *= -1;
transform.localScale = theScale;
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.layer == LayerMask.NameToLayer("Ground"))
{
isGrounded = true;
}
}
}
Answer the question
In order to leave comments, you need to log in
The value +-3.949388e-09 is very small. Typically, these artifacts occur due to operations on floats, and this is due to the bit representation and implementation of floats. If it does not affect the game mechanics - I would score.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question