- Home /
GameObject jitter at endPosition
public class InputController : MonoBehaviour
{
bool loadMainMenu = false;
public float speed = 1.5f;
private Vector3 _target;
private Vector3 _dir;
private Rigidbody2D _rb;
// Use this for initialization
void Start()
{
_target = transform.position;
_rb = GetComponent<Rigidbody2D>();
}
void FixedUpdate()
{
Debug.Log(_target);
_dir = (_target - transform.position).normalized * speed;
_rb.velocity = _dir;
Debug.Log(transform.position);
}
void LateUpdate()
{
if (Input.GetMouseButtonDown(0))
{
_target = Camera.main.ScreenToWorldPoint(Input.mousePosition);
_target.z = transform.position.z;
}
}
}
}
I attached this script to a Player and the movements are responding to the mouse clicks smoothly. However, once the player ends up at the clicked position, it starts to jitter. I've tried interpolation, it only put the jitter in slow-mo lol.
The player has a rigidbody and collider attached to it. This game is a 2D game.
Answer by Bunny83 · Aug 13, 2016 at 07:45 PM
Well you will never exactly reach your target. Each physics frame you just move "towards" the target point if you are already very close to the target you will "overshoot" the target. The next frame the direction will point in the opposite direction since you're now on the other side and you will move backwards. So your object oscillates around the target. You should detect if you reached the target and set the position to the target if you're close enough to the target.
void FixedUpdate()
{
var dir = _target - transform.position;
var dist = dir.magnitude;
if (dist < speed * Time.fixedDeltaTime)
{
_rb.MovePosition(_target);
dir = Vector3.zero;
}
else
dir /= dist; // normalize "dir"
_rb.velocity = dir * speed;
}
This will check the distance to the target and if it's too close (smaller than the distance it would travel in one physics frame) it simply puts the object at the target position and sets the direction to (0,0,0). Since we have already calculated the length of the "dir" vector we can manually normalize it to save the additional square root ^^.
I see! Thanks, the script worked. However, I'm getting these errors, which doesn't affect the script, but I'm assu$$anonymous$$g is a easy fix. Rigidbody2D.velocity assign attempt for 'PlayerPrefab(Clone)' is not valid. Input velocity is { NaN, NaN }. UnityEngine.Rigidbody2D:set_velocity(Vector2) Assets.Scripts.Controllers.InputController:FixedUpdate() (at Assets/Scripts/Controllers/InputController.cs:50)
Got it, in the normalizing step, we have to make sure we're not dividing by zero :p
if (dist != 0)
{
_dir /= dist; // normalize "dir"
}
Yes, i forgot the "else" ^^. I'll edit my answer.
Two years later... You helped me a lot with the ridiculous jittering in the move of my player. Thanks a lot for this little help!!