Keep Object In BoundsHow to Keep The Player Within Screen Boundaries

Author Waldo
Published June 28, 2018

In this tutorial I explain how to force your sprite to stay within the screen limitations using just a few lines of code.

Video Walkthrough

  • 0:35 - Scene Setup
  • 1:05 - Calculate Screen Boundaries
  • 1:30 - Create a new C# script
  • 2:10 - Calculate Screen Boundaries in World Space
  • 2:45 - Limit our object's center point to the screen boundaries
  • 3:45 - Calculate Object Boundaries
  • 4:15 - Clamp our object to the screen boundaries

Source Code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class boundaries : MonoBehaviour {
    private Vector2 screenBounds;
    private float objectWidth;
    private float objectHeight;

	// Use this for initialization
	void Start () {
        screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z));
        objectWidth = transform.GetComponent<SpriteRenderer>().bounds.size.x / 2;
        objectHeight = transform.GetComponent<SpriteRenderer>().bounds.size.y / 2;
	}

	// Update is called once per frame
	void LateUpdate(){
        Vector3 viewPos = transform.position;
        viewPos.x = Mathf.Clamp(viewPos.x, screenBounds.x + objectWidth, screenBounds.x * -1 - objectWidth);
        viewPos.y = Mathf.Clamp(viewPos.y, screenBounds.y + objectHeight, screenBounds.y * -1 - objectHeight);
        transform.position = viewPos;
	}
}

This tutorial is sponsored by this community

In order to stick to our mission of keeping education free, our videos and the content of this website rely on the support of this community. If you have found value in anything we provide, and if you are able to, please consider contributing to our Patreon. If you can’t afford to financially support us, please be sure to like, comment and share our content — it is equally as important.

Join The Community

Discussion

Browse Tutorials About