Transform.position as a Boundary?

Hi guys,

I’m an artist who is using Unity (love it) and familiarizing myself with C#. I’m pretty new to scripting, but here’s my situation:

I have a Starfox style type shooter, with a ship attached to a GameObject that travels forward (Z Axis) at constant rate. Currently, that ship can move freely in the X/Y, but I want to limit the amount that it can move in the X/Y so it doesn’t go off the camera view.

Here’s my code:

void Update ()
	{
		float horizontal = Input.GetAxis("Horizontal");
		float vertical = Input.GetAxis("Vertical");

		Vector3 direction = new Vector3(Input.GetAxis ("Horizontal"),invert*Input.GetAxis("Vertical"),0);
		Vector3 finalDirection = new Vector3(horizontal,invert*vertical,5.0f);
		
		transform.position += direction*bankMultiply*movementSpeed*Time.deltaTime;
		
		Vector3 boundaryVector = transform.position;

		//Testing Boundaries
		if(boundaryVector.x < -4.5f)
		{
			boundaryVector.x += -4.5f;	
		}

With this test, nothing changed. I was still able to fly past -4.5 on the X axis. Any ideas?

Thanks!

Your issue is line 16. In particular you are using “+=” in the assignment, which adds the right hand values to the left hand values. So the first frame after x goes below -4.5, you add -4.5 which evaluates to approximately -9. Every frame after that you subtract an additional -4.5. You can fix your problem by removing the ‘+’ sign:

boundaryVector.x = -4.5f;

If you camera is centered on the ‘x’ axis, then you can use Mathf.Clamp() to handle both positive and negative values:

boundaryVector.x = Mathf.Clamp(boundaryVector.x, -4.5f, 4.5f);

Note if the distance between the camera and your ship varies, you will need a more complex algorithm to keep the ship on the screen.