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 
            bc.Value.gameObject.AddComponent<BoxCollider2D>();
            //give the objects a name
            bc.Value.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);
            else
                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 Sujit Horakeri

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.
Connect with him on:
    Blogger
    Facebook

2 comments:

  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

    ReplyDelete


  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

    ReplyDelete