Layer Based Collision Detection

Objective:In Unity Layer-Based collision detection, which is a way to make Game Objects collide with another specific Game Objects that are tied up to specific layers.

Setp:1 Create Layers

          Go to Edit ->Project Settings->Tags And Layers and create two Layer

Layer1 and Layer2.

Step:2 Setting GameObjects to detect Collisions Based on Layers.

Set GameObject Collision Matrix.In the below Image show’s up LAYER1 collide with LAYER2,LAYER2 not collide with LAYER2 and LAYER1 not collide with LAYER1

Step:3 Create Player Cube And set Component like below image

Set Player  Layer to “Layer1” and Player Tab to “Player” and add the DragObject.cs and Player Collision Detection.cs and set the references.

Step:4 Create 2 Enemy Cubes  And set Component like below image

 

Create Enemy Cube and set the layer to “Layer2” and  tag to “Respawn” and add DragObject.cs

Step 5 : Create DragObject.cs Script and attach to enemy and player Game Objects.

using UnityEngine;
using System.Collections;
public class DragObject : MonoBehaviour {
    private Vector3 screenPoint;
    private Vector3 offset;  
    float z=0f;
    void Start(){
        z=transform.position.z;
    }
    //detect mouse down
    void OnMouseDown()
    { 
        //convert world point to screen point
        screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
        offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
    }
    //detect mouse drag
    void OnMouseDrag() 
    {  
        //set object position as like mouse position
        Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
        Vector3 curPosition   = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
        curPosition.z=z;
        transform.position = curPosition;
    }
        
}

Step 6 : Create PlayerCollisionDetection.cs Script and attach to Game Objects.

using UnityEngine;
using System.Collections;
public class PlayerCollisionDetection : MonoBehaviour {
    public UnityEngine.UI.Text collisionText;
    // Use this for initialization
    void Start () {
    }
    // Update is called once per frame
    void Update () {
    }
    //detect Collision
    void OnCollisionEnter(Collision collisionInfo){
        //print collided object name
        collisionText.text="Collide With : "+collisionInfo.gameObject.name;
    }
}

I hope you enjoyed this blog. Best of luck

Let's Think together, Say Something !