Skip to content

Tutorial on Physics Events in Unity.

james tichenor edited this page Jun 27, 2018 · 16 revisions

Tutorial on Physics Events in Unity

One of the unique aspects of working in Unity is that it has a built in physics engine. Leaning to think through this engine will allow you to build more in Unity. Today we are just going to quickly go over the physics event system and how it connects with code we can integrate it with what have learned so far.

Files

The assets in this tutoiral are simple enough that we can make them on the fly. For a finished version of this please download it here: Link to files

Outline:

  • Build initial elements the egg and the floor
  • Elongate the sphere to an egg shape
  • Add a rigid body component to the egg shape
  • Add a platform so the egg rolls down
  • Make a Collision Events Script on the Egg object
  • Create a Clone Script to add more eggs
  • Create Public Game Objects for Object to Clone and Start
  • Create Instantiate on Spacebar
  • Move Instantiate to its own Method
  • Use Cloning Script from Egg Object
  • Activate on exit of floor

Build initial elements the egg and the floor

unity screenshot

To the scene add a sphere and a box (GameObject -> 3DObject ->Sphere , GameObject -> 3DObject ->Cube) move the sphere to be floating above the box but still in the camera view (I just eyeballed it clicking and dragging with the objects and using Move command on the interface)

Elongate the sphere to an egg shape

Unity Screenshot

Elongate the box to to a floor shape and rename them both. (I just eyeballed it clicking and dragging with the objects and using Move command on the interface)

Add a rigid body component to the egg shape

Unity Screenshot Unity Gif

Add a rigid body component to the egg shape through add component. his play and your egg should now fall to the floor.

Add a platform so the egg rolls down

Unity Gif

Add a new gameObject of a box and position it as a platform in between the egg and the floor tilted so the egg will roll off the platform and land on the floor below and then roll of the whole floor.

Make a Collision Events Script on the Egg object

Unity Gif

So make a new script call Collision Events on the Egg object. To this script we will add 3 functions. If this is working when you hit play it will print that it has hit an object.

	void OnCollisionEnter(Collision collision){
		Debug.Log("colliion started");
	}

	void OnCollisionStay (Collision collision){
		Debug.Log("Stay occuring..");
	}

	void OnCollisionExit (Collision collision)
	{
		Debug.Log("Exit called...");
	}

Add a starting Point for our clones

add Cylinder gif

Add a cylinder to the scene and locate it where our egg is right now

Create a Clone Script to add more eggs

create cloner Script gif

Create this script on an empty game object that we will rename Cloner. We will make this script called AddElements with public variables for the GameObjects so that we can drag and drop what we want to clone. Lets start by just making sure we can get spacebar input by adding this to your new Clone Script

    void Update()
    {
        if (Input.GetKeyDown("space"))
        {
            Debug.Log("spacebar");
        }
    }

Create Public Game Objects for Object to Clone and Start

add objects to clone and where to start gif

Now we are going to create the public game objects. Making these Public allow us to drag and drop objects in the scene to clone. What we will do is make an object called startGo for the starting position GameObject and we will make an object call copyGo for the game object we are going to copy. Once we have added this to the script and if it all compiles then they will show up in the interface. Then we are going to drag and drop the Cylinder onto the startGo object slot and the Egg onto the copyGo slot.

public class AddElements : MonoBehaviour {
	public GameObject startGo;
	public GameObject copyGo;

Create Instantiate on Spacebar

Make eggs start on spacebar

Now we will make a script that will Instantiate aka create a clone off the object we have added as copyGo We also need to turn off the capsule collider component of the cylinder object so the eggs don't collide with it but rather come out from it.

public class AddElements : MonoBehaviour {
	public GameObject startGo;
	public GameObject copyGo;

    void Update()
    {
        if (Input.GetKeyDown("space"))
        {
            Debug.Log("spacebar");
	    Vector3 startPos;
            Quaternion startRotation;

	    startPos = startGo.transform.position;
            startRotation = startGo.transform.rotation; 
	    Instantiate(copyGo,startPos,startRotation);
        }
    }

Move Instantiate to its own Method

Lets more the Instantiate out of the keydown for spacebar and into its own method so we can call it from another script. The idea is we will call this script when we know the egg exits collision with the floor object.

	public void makeObject ()
	{
		//Debug.Log("Make object called");
		Vector3 startPos;
		Quaternion startRotation;

		startPos = startGo.transform.position;
		startRotation = startGo.transform.rotation; 
		Instantiate(copyGo,startPos,startRotation);
	}

Use Cloning Script from Egg Object

What we are going to do here is add a public gameObject call clone script to our collisionFlags script on Egg. This will allow us to drag and drop the Cloner game object to this script. Then we get the script component of that game object and call the makeObject function of that script. Since this on the OnCollisonExit script this will occur every time an object exits collision with another game object. Now the problem with this script is that it will occur not only the time it finished colliding with the floor but also when it rolls off of the platform or if two eggs touch. So often this script will cause an exponential number of eggs to be drawn and for Unity to crash. But this is informative to do so i recommend saving your project and trying this out.

	public GameObject cloneScript;
	
	void OnCollisionExit (Collision collision)
	{
	//	Debug.Log("Exit called...");
	cloneScript.GetComponent<AddElements>().makeObject();
	
	}

Activate on exit of floor

eggs when eggs fall off floor gif

To make this work well what we will do is check to see if we have rolled of the the floor and only if our collision object has the name floor do we create a new object.

	public GameObject cloneScript;
	
	void OnCollisionExit (Collision collision)
	{
           if(collision.gameObject.name == "Floor")        
              {
	      //	Debug.Log("Exit called...");
	       cloneScript.GetComponent<AddElements>().makeObject();
	     }
        }

Congratulation All the Eggs You Could Want

All the eggs you want gif

Resources and Notes

https://unity3d.com/learn/tutorials/topics/physics/detecting-collisions-oncollisionenter

https://unity3d.com/learn/tutorials/topics/physics/rigidbodies

https://unity3d.com/learn/tutorials/topics/scripting/getbutton-and-getkey

-end

Clone this wiki locally