Hi,
I’m new to Unity and programming in general, when possible i follow tutorials and try to get answers to my noob questions googling and hoping someone had the same issue before, but this time I couldn’t find any answer solving a similar problem.
In the Space Shooter Unity tutorial, the movement of the spaceship is bound to the camera view by using the Mathf.Clamp function.
This is the code:
[System.Serializable]
public class Boundary
{
public float xMin, xMax, zMin, zMax;
}
public class PlayerController : MonoBehaviour
{
public float speed;
public Rigidbody rb;
public Boundary boundary;
void FixedUpdate ()
{
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
Vector3 movement = new Vector3 (moveHorizontal, 0.0F, moveVertical);
rb.velocity = movement * speed;
rb.position = new Vector3
(
Mathf.Clamp (rb.position.x, boundary.xMin, boundary.xMax),
0.0F,
Mathf.Clamp (rb.position.z, boundary.zMin, boundary.zMax)
);
}
}
The Rigidbody is attached to the spaceship 3D model, and the xMin, xMax, zMin, zMax and speed values are user-defined in the inspector.
Now the code works almost perfectly, with the exception that, when reaching the border limits (e.g… -6 and 6 in the x axis), the spaceship slightly overlaps this limit (-6.2, 6.2), returning to the limit values when you stop pressing the movement buttons.
The excess movement (over the bounds) is affected by changing the speed amount, so i guess it must be something related to Physics, RigidBody, velocity or similar…
I guess if there’s a way to limit the movement exactly to the values in the Mathf.Clamp function or if a total different approach has to be used.
Thanks in advance.