Search code examples
c#unity-game-engineunity3d-2dtools

How to find out if something will collide with something in Unity (2D)


I am trying to make a 2D game in Unity and I was curious if there is a way to check if there WILL be a collision between 2 objects rather then telling me WHEN they actually collide.

For Example - I am making a Space Invaders game and I want to check if any one of the space invaders on the edges will collide with a edge before they actually move in a C# script. I coded in Game Maker Studio and I remember that function being available but I am having a hard time finding out if its possible in Unity. Is this possible in Unity?

Thanks for the help.


Solution

  • yes its possible, you would have to do some sort of raycasting in the direction that the gameobject is moving you can check This Link for Physics.Raycast to see how to go about doing what youd like

    using UnityEngine;
    using System.Collections;
    
    public class ExampleClass : MonoBehaviour {
        void Update() {
            Vector3 fwd = transform.TransformDirection(Vector3.forward);
            if (Physics.Raycast(transform.position, fwd, 10))
                print("There is something in front of the object!");
    
        }
    }