How to Generate Colliders along the edges of the screen - Unity (C#)

How to Generate Colliders along the edges of the screen - Unity (C#)

There are times where in we would like to restrict the player (object/enemy) movement to be within our screen, i.e., we would want the object to bounce off the Screen walls just like in the Ping Pong game.

There are many ways in which we can achieve this, I will be demonstrating one way where in we would add colliders to the screen edges. The good thing about this is that the colliders are generated through script and are dependent on the Camera size. Basically, you need not worry about the size of the screen where your game would be played on, it's all taken into account by the script that we will be writing.

In short, we will be seeing How to Generate Colliders along the edges of the screen

Create a new C# script named GenerateColliders and attach it to whatever object you would wish to (I prefer the Main Camera though). Open the script and add the below code to it:

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

public class GenerateColliders : MonoBehaviour {

    public float widthOfCollider = 2f;
    public float z_axis = 0f;
    private Vector2 screenSize;

    void Start ()
 //Create a Dictionary to hold the transforms and their names
        Dictionary<string,Transform> colliders = new Dictionary<string,Transform>();
        //Create GameObjects and add their Transform components to the Dictionary created above
        colliders.Add("Top",new GameObject().transform);
        colliders.Add("Bottom",new GameObject().transform);
        colliders.Add("Right",new GameObject().transform);
        colliders.Add("Left",new GameObject().transform);
 //Claculate world space screenSize based on the MainCamera position
        Vector3 cameraPos = Camera.main.transform.position;
        screenSize.x = Vector2.Distance (Camera.main.ScreenToWorldPoint(new Vector2(0,0)),Camera.main.ScreenToWorldPoint(new Vector2(Screen.width, 0))) * 0.5f;
 screenSize.y = Vector2.Distance (Camera.main.ScreenToWorldPoint(new Vector2(0,0)),Camera.main.ScreenToWorldPoint(new Vector2(0, Screen.height))) * 0.5f;
    //loop through the transforms in colliders
        foreach(KeyValuePair<string,Transform> bc in colliders)
     //Add the collider component 
            //give the objects a name
   = bc.Key + "Collider";
     //Make the object with collider child of the object this script is attached to
            bc.Value.parent = transform;
      //Scale the object to the width and height of the screen
            if(bc.Key == "Left" || bc.Key == "Right")
                bc.Value.localScale = new Vector3(widthOfCollider, screenSize.y * 2, widthOfCollider);
                bc.Value.localScale = new Vector3(screenSize.x * 2, widthOfCollider, widthOfCollider);
 //Change position of the objects to align perfectly with outer-edge of screen
        colliders["Right"].position = new Vector3(cameraPos.x + screenSize.x + (colliders["Right"].localScale.x * 0.5f), cameraPos.y, z_axis);
        colliders["Left"].position = new Vector3(cameraPos.x - screenSize.x - (colliders["Left"].localScale.x * 0.5f), cameraPos.y, z_axis);
        colliders["Top"].position = new Vector3(cameraPos.x, cameraPos.y + screenSize.y + (colliders["Top"].localScale.y * 0.5f), z_axis);
        colliders["Bottom"].position = new Vector3(cameraPos.x, cameraPos.y - screenSize.y - (colliders["Bottom"].localScale.y * 0.5f), z_axis);

Save the script and return to Unity, test the scene to notice that there are colliders generated along the screen edges.

How to Generate Colliders along the edges of the screen - Unity (C#)

Note that since the code is placed in Start method, the collider positions won't update if you try changing the screen resolution while testing the scene.

See you around.
Share on Google+

About Unknown

Sujit Horakeri is a game freak just like any other next door guy you would come across. He is a Web Developer by Profession, Game Developer by Choice.


  1. hey guys.....
    i want to implement that my player automatically detects the zigzag object and reach to its end.......
    for example , a way from snakes' mouth to its tail
    how would i..... any help plzzzzzzzzzzzzzzz


  2. If you own the magnificent LG G6 smartphone, then you must be wandering how to protect this expensive phone with a cover that would look chic as well as provide protection to accidental drops and other hazards. Well you have to look no further as I have a well comprised list of some of the best LG G6 phone covers. Just have a look at my site here for all the information LG G6 Cases

  3. Wonderful article, thanks for putting this together! This is obviously one great post. Thanks for the valuable information and insights you have so provided here.
    Bitcoin To Dollar Dogecoin Mining

  4. This is a wonderful article, So much info given in it, These type of articles keeps the users interest in the website, keep on sharing more... good luck

  5. Great answer, very nice that you give such answer here.

  6. Your post is great and meaningful. Thank you for sharing this article. I would like to receive better and better articles.
    the impossible quiz

  7. Ahh that is great thank you ! Good for special needs too ! best novel updates

  8. That suggestions should appear more often.


  9. It has been simply incredibly generous with you to provide openly what exactly many individuals would’ve marketed for an eBook to end up making some cash for their end, primarily given that you could have tried it in the event you wanted.
    Data Science Course in Chennai | NO.1 Data Science Training in Chennai
    Python Course in Chennai | NO.1 Python Training Institutes in Chennai
    RPA Course in Chennai | NO.1 RPA Training in Chennai
    Digital Marketing Course in Chennai | NO.1 Digital Marketing Training in Chennai

  10. Excellent blog I visit this blog it's really awesome. The important thing is that in this blog content written clearly and understandable. The content of information is very informative.
    oracle fusion financials classroom training
    Workday HCM Online Training
    Oracle Fusion Financials Online Training
    Oracle Fusion HCM Online Training
    Oracle Fusion SCM Online Training
    Oracle Fusion HCM Classroom Training