- Home /
Mouse input lag causes line rendering jitter
I have
a 2D sprite that moves with a rigidbody2d,
mouse input that provides a location in world space,
a line renderer that draws a line between the sprite and mouse point.
When my sprite moves, the line jitters badly. I've attached a gif.
https://giphy.com/gifs/l3q2xdNZjKrlRlYu4
This is the simplest project that reproduces this error. Code sample below:
void Update() {
var moveInput = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
var rawMousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
lookPosition = new Vector3(rawMousePosition.x, rawMousePosition.y, 0);
lineRenderer.SetPosition(0, transform.position);
lineRenderer.SetPosition(1, lookPosition);
}
void FixedUpdate() {
rigidBody2d.velocity = moveInput.normalized * moveSpeed;
}
Moving the sprite directly using it's transform, the line doesn't jitter, but the line still noticeably lags behind the mouse point.
https://giphy.com/gifs/l3q2Qwi29hWeSkG5y
void Update() {
var moveInput = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
transform.Translate(moveInput * moveSpeed * Time.deltaTime);
var rawMousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
lookPosition = new Vector3(rawMousePosition.x, rawMousePosition.y, 0);
lineRenderer.SetPosition(0, transform.position);
lineRenderer.SetPosition(1, lookPosition);
}
I can accept the line lagging behind the mouse point in the 2nd scenario; my question is how do I prevent the jitter in the 1st scenario, given that I'm moving rigidbodies in my 2D project?
Answer by FortisVenaliter · Feb 17, 2017 at 09:01 PM
It most likely has to do with the update order. You're probably updating the line position before the rigidbody updates the position. That would give you the jitter. Try moving your line update code to LateUpdate(); Read here for more info.
I had the same problem and this fixed it for me. Thanks!
Had the same issue. Spent 2 days trying to fix this and your solution is a life savior even after 3 years! Thank you!
Your answer
Follow this Question
Related Questions
Mouse Input Lag 3 Answers
Smoothen Mouse Axis Input 2 Answers
Rigidbody interpolation problem 0 Answers
Input System Can't Catch Event on Update 0 Answers
How can I detect the mouse is moving through code? 3 Answers