Trying to restrict movement to bounds of screen using MathF.Clamp()

I’m new to Unity and am following a book with examples. This one creates a spaceship shooter game. I want to restrict the spaceship to only be able to go within the screen view. I’ve used the following code:

public class BoundsLock : MonoBehaviour
{

    private Transform ThisTransform = null;

    // can be changed from inspector
    public Vector2 HorzRange = Vector2.zero;
    public Vector2 VertRange = Vector2.zero;

    // use this for initialization
    void Awake()
    {
        ThisTransform = GetComponent<Transform>();

    }

    // Update is called once per frame
    void LastUpdate()
    {
        // clamp position
        ThisTransform.position = new Vector3(Mathf.Clamp
            (ThisTransform.position.x, HorzRange.x, HorzRange.y),
            ThisTransform.position.y,
            Mathf.Clamp(ThisTransform.position.z, VertRange.x, VertRange.y));
    }
}

Problem is the ship still goes out of the screen and gets lost. What am I doing wrong?

  • is LateUpdate not LastUpdate, change this

  • you never really get the image bounds, HorzRange and VertRange is still zero, that depends of your own way to proyect the camera

    void LateUpdate()
    {
    Camera cam = Camera.main;
    Vector3 bottomLeft = cam.ScreenToWorldPoint(new Vector3(0f, 0f, transform.position.y));
    Vector3 topRight = cam.ScreenToWorldPoint(new Vector3(cam.pixelWidth, cam.pixelHeight, transform.position.y));
    //convert to your way to do this
    HorzRange = new Vector2(bottomLeft.x, topRight.x);
    VertRange = new Vector2(bottomLeft.y, topRight.y);
    //I just copy & paste your code here
    transform.position = new Vector3(Mathf.Clamp
    ( transform.position.x, HorzRange.x, HorzRange.y),
    transform.position.y,
    Mathf.Clamp( transform.position.z, VertRange.x, VertRange.y));
    }

  • you dont need to store a thisTransform , use built in transform

Try clamping it before assigning the position. Something like this:

Vector3 newPos = //clamped values;
transform.position = newPos;

Also you can take out some of the “fluff”. You can refer to the transform of the current gameobject without using get component or that “ThisTransform” reference. Just use: transform.position (or whatever). Also I think you’re missing the “z” component in your clamped vector3 (not sure cause my phone is cutting it off). One last thing, any reason this code isn’t just in the “Update” ?

This is a screen shot best i could get from video, its missing from top

using UnityEngine;
public class Player:MonoBehaviour{
  [SerializeField]float moveSpeed=10f;

  float xMin
  floatxMax;
  void Start(){
     SetUpMoveBoundries();
  }

and how do they differ:

133251-temppic2.png