Keeping 3D Object bounded by screen height and width

Hi I’m following a udemy tutorial and making a game called argon assault, for reference since its a popular course I’ve found online someone who has made a version of the game:

The course however does shows a dirty hack for restricting the ship within the screen, And for practice I want to do it using code.

I’ve tried using the code from the following tutorial:

But for some reason the range in which it limits my ship is way larger than my screen and I can’t figure out why, here is my code:

public class PlayerController : MonoBehaviour
{
    [SerializeField] float controlSpeed = 30f;

    private Vector2 screenBounds;

    void Start()
    {
        screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));
        Debug.Log("Screen bounds: " + screenBounds);
    }
    void Update()
    {
        float xThrow = Input.GetAxis("Horizontal");
        float yThrow = Input.GetAxis("Vertical");


        float xOffSet = xThrow * Time.deltaTime * controlSpeed;
        float rawXPos = transform.localPosition.x + xOffSet;
        float clampedXPos = Mathf.Clamp(rawXPos, screenBounds.x * -1, screenBounds.x);


        float yOffSet = yThrow * Time.deltaTime * controlSpeed;
        float rawYPos = transform.localPosition.y + yOffSet;
        float clampedYPos = Mathf.Clamp(rawYPos,  screenBounds.y * -1, screenBounds.y);


        transform.localPosition = new Vector3(clampedXPos, clampedYPos, transform.localPosition.z);
    }
}

I think its also worth mentioning that the ship is a child object to an empty parent object that is used for timeline animations, hence the use of locaposition in some of the code.

Inlcuding the main camera also being a child to the same parent object.

Hey!

I think what happens is that your issue is due to the fact that you mix the world coordinate system with a local coordinate system.

localPositon gives you the data about the position relative to the parent object. This is probably why your system doesn’t work. You should try getting the worldPositon when checking if your object is outside of the screen bounds or not.

If you want to create such a system you could calculate the bottom-left and the top-right world coordinates of your screen. Next all you need to do is just before you move your ship check if the end position that you will achieve will be inside the bounds (comparing the x and Y of both points).

You can view this article about the screen coordinate system so that you have some better idea on how to find the top-down and bottom-right points.

I hope it helps!

1 Like