Keep Object In BoundsHow to Keep The Player Within Screen Boundaries

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

In this video you will learn how to:

  • 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;
	}
}

LINK TO THIS POST

SHARE THIS POST


DISCUSSION