I've been searching on the API, but haven't found anything yet. I'm looking for a way to do the following:
function OnRayCollision()
{
//Do some stuff
}
I've been searching on the API, but haven't found anything yet. I'm looking for a way to do the following:
function OnRayCollision()
{
//Do some stuff
}
Rays don't move at a speed. They also don't stick out from things like infinite lasers. If you want something like that, then Raycast every frame.
http://unity3d.com/support/documentation/ScriptReference/Physics.Raycast.html
http://unity3d.com/support/documentation/ScriptReference/Collider.Raycast.html
See Physics.Raycast and Physics.RaycastAll.
A simple skeleton for a ray collider could be like this:
// RayCollider.cs
using UnityEngine;
using System.Collections;
public class RayCollider : MonoBehaviour
{
public LayerMask layers = -1;
public float distance = float.PositiveInfinity;
public bool blocking = true;
const SendMessageOptions options = SendMessageOptions.DontRequireReceiver;
const string callback = "OnRayCollision";
void Update()
{
Ray ray = new Ray(transform.position, transform.forward);
if (blocking)
{
RaycastHit hit;
if (Physics.Raycast(ray, out hit, distance, layers))
{
var info = new RayCollision(this, hit);
SendMessage(callback, info, options);
hit.collider.SendMessage(callback, info, options);
}
}
else
{
var hits = Physics.RaycastAll(ray, distance, layers);
foreach (var hit in hits)
{
var info = new RayCollision(this, hit);
SendMessage(callback, info, options);
hit.collider.SendMessage(callback, info, options);
}
}
}
}
public struct RayCollision
{
public RayCollider ray;
public RaycastHit hit;
// For ease of use...
public Collider collider
{
get { return hit.collider; }
}
public RayCollision(RayCollider ray, RaycastHit hit)
{
this.ray = ray;
this.hit = hit;
}
}
And an example script responding to the ray collision could be something like
// DeathByRay.cs
using UnityEngine;
using System.Collections;
public class DeathByRay : MonoBehaviour
{
void OnRayCollision(RayCollision rayCollision)
{
if (rayCollision.ray.CompareTag("Death Star"))
Destroy(gameObject);
}
}
Or JS version:
// DeathByRay.js
function OnRayCollision(rayCollision : RayCollision)
{
if (rayCollision.ray.CompareTag("Death Star"))
Destroy(gameObject);
}
Both the RayCollider and the object having the hit collider will have OnRayCollision called. The structure passed contains the ray that cast the collision and the raycast hit information. Note that this doesn't mean it pushes things around. This is sort of a trigger, only raycasted.