unity on collision 2d code example
Example 1: unity oncollisionenter2d
void OnCollisionEnter2D(Collision2D col)
{
Debug.Log("Collided");
}
Example 2: unity raycast 2d
using UnityEngine;public class Example : MonoBehaviour
{
public float liftForce;
public float damping;
void Start()
{
rb2D = GetComponent<Rigidbody2D>();
} void FixedUpdate()
{
RaycastHit2D hit = Physics2D.Raycast(transform.position, -Vector2.up);
if (hit.collider != null)
{
float distance = Mathf.Abs(hit.point.y - transform.position.y);
float heightError = floatHeight - distance;
float force = liftForce * heightError - rb2D.velocity.y * damping;
rb2D.AddForce(Vector3.up * force);
}
}
}
Example 3: oncollisionenter2d
using UnityEngine;
using System.Collections;public class ExampleClass : MonoBehaviour {
void OnCollisionEnter2D(Collision2D coll) {
if (coll.gameObject.tag == "Enemy")
coll.gameObject.SendMessage("ApplyDamage", 10);
}
}
Example 4: unity 2d collision
void OnCollisionEnter2D(Collision2D col) {
Debug.Log("Collided with: " + col.gameObject.name);
}
Example 5: collision detector unity c# 2d
void OnCollisionEnter2D(Collision2D coll){)