Clamped position, but Velocity not stopping.
I'm trying to make some sort of space shooter. Much like the one in the Unity tutorials. And like that tutorial, I've scripted the rigid body to rotate in accordance with the direction of the velocity. You will notice though, that in that tutorial, when the rigid body runs up against the invisible boundary (thanks to clamps on position values) the rigid body is still rotated despite having come to a stop. I scripted in a display window constantly showing the velocity of the rigid body, and found that even while it has come to a stop, the velocity will not fall back to zero until the input button is released. This is very confusing. Velocity is meant to measure the direction and magnitude of an object's movement. Why do I still get velocity even though the clamped position has brought the object to a stand-still?
using System.Collections; using UnityEngine.UI; // using System.Collections.Generic; using UnityEngine;
[System.Serializable] public class Boundary{ public float xMax, yMax, yMin; }
[System.Serializable] public class Tilt{ public float tiltX, tiltY, tiltZ; }
public class PlayerMovement : MonoBehaviour {
private float speed; //
public float thrust;
private Rigidbody rb;
public Boundary boundary;
public Tilt tilt;
void Start () {
rb = GetComponent<Rigidbody> ();
}
void FixedUpdate () {
speed = rb.velocity.magnitude; //
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
Vector3 movement = new Vector3 (moveHorizontal, moveVertical, 0.0f);
rb.AddForce (movement * thrust);
//Clamp movement input values to restrict rigidbody from leaving play area.
rb.position = new Vector3 (
Mathf.Clamp (rb.position.x, -boundary.xMax, boundary.xMax),
Mathf.Clamp (rb.position.y, boundary.yMin, boundary.yMax),
0
);
//Have rotation values of rigidbody correspond to direction velocity of rigidbody.
rb.rotation = Quaternion.Euler (
rb.velocity.y * tilt.tiltX,
-rb.velocity.x * tilt.tiltY,
-rb.velocity.x * tilt.tiltZ
);
}
void OnGUI() { //
GUI.Box (new Rect (10, 10, 100, 90), "Measurements"); //
GUI.Label (new Rect (20, 40, 80, 20), speed + "m/s"); //
}
}
Could it be that the clamp value is simply detected when my rigid body passes beyond the clamped value and pushes it back, only for it to pass beyond the clamp value again, and so on indefinitely? Thus a tiny amount of movement is still occurring? Either that, or Velocity is not simply the readable value of an object's movement like I thought it was.