Home > Enterprise >  Why is rigidBody.velocity not very accurate in my unity2d project?
Why is rigidBody.velocity not very accurate in my unity2d project?

Time:11-15

I was trying to make my object change direction when it moves by 1 unit, so i set its rigidbody.velocity to be 0.25, and set a coroutine that changes its direction every 4 seconds. But i noticed that it has some small inaccuracies (such as changing direction when moved by 0.998), which builds up to a lot after running for some time.

Now I know the best way is probably to just directly change transform.position in this case, but could someone tell me why does my previous method have these inaccuracies?

Edit:

To add a bit of context, im trying to replicate a traditional snake game but with smooth movement(in stead of jumping between the grids). It was a bit hard to explain how the direction can only be changed when the snake has reached a whole unit so i just said that the direction is changed every 4 seconds in the original post. Here is the code

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

public class SnakeHead : MonoBehaviour
{
    private Rigidbody2D rigidBody;
    private Vector2 currDir;
    [SerializeField] private float speed;
    void Start()
    {
        rigidBody = gameObject.GetComponent<Rigidbody2D>();
        currDir = Snake.Instance.GetDir();
        StartCoroutine(Move());
    }

    IEnumerator Move()
    {
        while (GameManager.gameIsRunning)
        {
            currDir = Snake.Instance.GetDir();
            rigidBody.velocity = currDir * speed;
            yield return new WaitForSeconds(1 / speed);
        }
    }
}

note that i set speed to be 0.25 in the unity editor window.

im aware that changing transform.position directly is bad practice, but ive watched several tutorials and all of them did that on the snake's movement. Does anyone know if there's a better way?

CodePudding user response:

It's pretty hard to make it such that you change direction exactly after 4 seconds. Using WaitForSeconds(4) will not wait exactly 4 second, instead it will wait at least 4 seconds as correctly mentioned in the comments. It largely depends on how frequently your coroutine is checked by the engine.

As you already mentioned, it would probably be a good idea to do some explicit actions. Either moving it "by hand" (not through the physics simulation), or periodically set the position to a known value.

  • Related