- Home /
Clamping movement causes jittering
So I have a ship that moves like this:
void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal , moveVertical, Mathf.Max(rb.velocity.z, forwardSpeed));
rb.velocity = movement * speed;
transform.position = new Vector3
(
Mathf.Clamp(rb.position.x, moveBoundary.xMin, moveBoundary.xMax),
Mathf.Clamp(rb.position.y, moveBoundary.yMin, moveBoundary.yMax),
rb.position.z
);
transform.rotation = Quaternion.Euler(rb.velocity.y * -tilt, rb.velocity.x * tilt, rb.velocity.x * -tilt);
}
(moveboundary
is a Boundary
which just has 4 float parameters)
But when I bump the player against the boundary I get jittering. Should I not be using physics for this movement?
Answer by Ramlock · Mar 26, 2018 at 05:54 AM
The problem is that your velocity against the invisible wall is still greater than zero, therefore you're constantly going past it and having to be reset back. You should instead detect when the boundary has been reached and make sure your relative velocity is either zero or moving away from it.
Vector3 movement = new Vector3(moveHorizontal, moveVertical, Mathf.Max(rb.velocity.z, forwardSpeed));
Vector3 velocity = movement * speed;
Vector3 position = rb.position;
if (position.x < moveBoundary.xMin)
{
position.x = moveBoundary.xMin;
velocity.x = Mathf.Max(velocity.x, 0f);
}
else if (position.x > moveBoundary.xMax)
{
position.x = moveBoundary.xMax;
velocity.x = Mathf.Min(velocity.x, 0f);
}
if (position.y < moveBoundary.yMin)
{
position.y = moveBoundary.yMin;
velocity.y = Mathf.Max(velocity.y, 0f);
}
else if (position.y > moveBoundary.yMax)
{
position.y = moveBoundary.yMax;
velocity.y = Mathf.Min(velocity.y, 0f);
}
rb.velocity = velocity;
transform.position = position;
transform.rotation = Quaternion.Euler(rb.velocity.y * -tilt, rb.velocity.x * tilt, rb.velocity.x * -tilt);
PS: Also, make sure you do all this in the FixedUpdate, as it's the proper time and place to do physics calculations.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Need a simple car physics script working on unity 5? 1 Answer
Prefab Collider2D not Recognized as Raycast Collider 2 Answers
Distribute terrain in zones 3 Answers
Empty GameObjects fly away. 2 Answers