- Home /
Unsuccessfully trying to clamp my player object
Hi I am new to unity and am finding it very fun. However I've come across this issue and I I've tried a lot of fiddling around with this code but I just can't seem to stop the player from moving off of the screen.
What am I doing wrong here? I am making a top down facing arcade shooter. I don't want the spaceship to go beyond the edge of the screen (when in game mode).
public class PlayerController : MonoBehaviour {
public float xMin, xMax, zMin, zMax;
private Rigidbody rb;
public float speed;
// Use this for initialization
void Start () {
rb = GetComponent<Rigidbody> ();
}
// Update is called once per frame
void FixedUpdate () {
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
Vector3 movement = new Vector3(moveHorizontal,0.0f,moveVertical);
GetComponent<Rigidbody>().AddForce (movement);
rb.position = new Vector3 (Mathf.Clamp (GetComponent<Rigidbody>().position.x, xMin, xMax), 0.0f, Mathf.Clamp (GetComponent<Rigidbody>().position.z, zMin, zMax));
}
}
Thanks for the help.
Actually in this particular snippet the ship doesn't move at all (you see movement but it seems stuck). This is still not what I am ai$$anonymous$$g for.
Well, for one thing, where do you set the clamp values? In the inspector?
Second, you are only clamping the position, which means you may keep it inside for that frame, but it may still have velocity trying to push it out.
I solved this a while ago now. Thanks for the response though.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
What's a better way to code in chunks 1 Answer
C# basic perfomance question 2 Answers