Warning: Cannot modify header information - headers already sent by (output started at /var/www/lalieno.it/index.php:48) in /var/www/lalieno.it/inc/cookie.php on line 3
a cadenza discontinua
Come se fossi
BLOG

Unity 2D [E1] - Detecting Collisions

This is a mini tutorial in Unity 2D environment with the aim of simply explaining the management of collisions . There will be different , where we will explain the most common problems encountered in the development of 2D games .

The collision management is the basis of any video game , in Unity you can handle them in a very fast and intuitive . Suppose you have an object named " Box " with a sprite depicting a box .

In this item we applied , as well as the sprite , even a 2D Box Collider and a script that we will create . The inclusion of the BoxCollider2D makes possible the interception of collisions as well as the definition of the collision space via the "Edit Collider " .

We see in detail how to edit the script to handle the interception .

We have basically three methods : OnCollisionEnter2D , OnCollisionExit2D , OnCollisionStay who will receive as a parameter the Collision . This contains information about the collision respectively incoming , outgoing and in the act . The information is , for example, collision points , the speed etc ...

 

using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class BoxColliderScript : MonoBehaviour {

	// Use this for initialization
	void Start () {
	
	}
	
	// Update is called once per frame
	void Update () {

	}

	void OnCollisionEnter2D (Collision collisionInfo)
	{
		// points of collision
		foreach (ContactPoint contact in collisionInfo.contacts) {
			Debug.DrawRay(contact.point, contact.normal, Color.white);
		}

		// velocity
		//collisionInfo.relativeVelocity
	}

	void OnCollisionExit2D (Collision collisionInfo)
	{
		// exit collision object
		print("No longer in contact with " + collisionInfo.transform.name);
	}

	void OnCollisionStay(Collision collisionInfo) {

		// points of collision
		foreach (ContactPoint contact in collisionInfo.contacts) {
			Debug.DrawRay(contact.point, contact.normal, Color.white);
		}

	}

}

di GuiZ
23/02/2016

Commenta

We'll never share your email with anyone else.