I’m trying to set the boundaries for this game so the spaceship doesn’t move outside the play area. I have copied the code exactly (although I have had to make the changes set in the unity 5 update guide) but the spaceship doesn’t stop at the boundaries I set, it just slows down greatly but continues moving past the boundaries I’ve set. Can anyone please help?
My code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class Boundary
{
public float xMin, xMax, zMin, zMax;
}
public class PlayerController : MonoBehaviour {
private Rigidbody rb;
public float speed;
public Boundary boundary;
void Start ()
{
rb = GetComponent<Rigidbody>();
}
void FixedUpdate ()
{
float moveHorizontal = Input.GetAxis ("Horizontal");
float moveVertical = Input.GetAxis ("Vertical");
Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
rb.AddForce (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)
);
}
}