Skip to content

Instantly share code, notes, and snippets.

@AngryAnt
Created July 13, 2011 13:03
Show Gist options
  • Save AngryAnt/1080257 to your computer and use it in GitHub Desktop.
Save AngryAnt/1080257 to your computer and use it in GitHub Desktop.
An example of how interaction could be done. Untested code.
using UnityEngine;
public class InteractionExample : MonoBehaviour
{
public string interactionKey = "i";
public float interactionRadius = 2.0f, interactionViewCone = 60.0f;
void Update ()
{
if (Input.GetKeyDown (interactionKey))
{
Interact ();
}
}
void Interact ()
{
Collider[] colliders = Physics.OverlapSphere (transform.position, interactionRadius);
// Might want to apply a layer mask here, to reduce the cost of the query
if (colliders.Length < 1)
{
return;
}
float shortestDistance = Mathf.infinite;
GameObject closestInteractive = null;
foreach (Collider collider in colliders)
{
GameObject root = collider.transform.root;
Vector3 direction = root.transform.position - transform.position;
if (root.tag == "Interactive" && // Or whatever means you use for marking objects as interactive
Vector3.Angle (direction, transform.forward) < interactionViewCone
// Don't interact with stuff behind us
)
{
if (shortestDistance > direction.sqrMagnitude)
// Find the closest interactive object
{
shortestDistance = direction.sqrMagnitude;
closestInteractive = root;
}
}
}
if (closestInteractive != null)
// Interact if we found a good candidate
{
closestInteractive.SendMessage ("OnInteract");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment