- 最后登录
- 2014-10-23
- 注册时间
- 2011-7-19
- 阅读权限
- 90
- 积分
- 81303
- 纳金币
- -1
- 精华
- 11
|
What’s In This Space?
Another great use of triggers is to the answer a question for your game logic: What’s in this space? Perhaps you want your spawn points to fire only if they’re empty, or you want to see if two objects are near enough to count for something.
Here’s a concerete example: One of our games, Crane Wars, is a stacking game. In order to determine if different building pieces are stacked on top of one another, and should count as one building, we use triggers:
The slim box outlines on the top of the building pieces are the triggers. White indicates that nothing is in the trigger, and green–the bottom two floors of the stack–indicate that another building piece is in the trigger and is considered the “upstairs” piece in the sequence. The light blue box is a spawn point; it will spawn another piece as soon as it is empty.
In order to facilitate this game logic, we have generic scripts that track objects as they enter and leave a trigger. Unfortunately, there is no function available like collider.GetCollidersInsideTrigger(). Fear not, though, it’s fairly easy logic. The following script will track all objects that enter, and store them in a list based on their layer:
#pragma strict
@script AddComponentMenu(“Library/Physics/Trigger Track By Layer”)
/**
* Keep a list of all objects inside this trigger, available by layer
*
* Layer -1 is a list of all objects
*/
// should we track triggers too?
var trackOtherTriggers:boolean = false;
// objects we aren’t tracking
var ignoreColliders:Collider[];
// hashtable of arraylists for our objects
private var objects:Hashtable = new Hashtable();
/**
* Initialize internals
*/
function Awake()
{
// -1 is all layers
objects[-1] = new ArrayList();
}
/**
* Return an arraylist for a layer–if no layer, just make an empty one
*/
function GetObjects(layer:int):ArrayList
{
var list:ArrayList = objects[layer];
// scrub any nulls when scripts request a list
if(list)
{
Helpers.ClearArrayListNulls(list);
return list;
}
else
return new ArrayList();
}
/**
* Record when objects enter
*/
function OnTriggerEnter(other:Collider)
{
if(!trackOtherTriggers && other.isTrigger)
return;
// is this collider in our ignore list?
for(var testIgnore:Collider in ignoreColliders)
if(testIgnore == other)
return;
var go:GameObject = other.gameObject;
var layer:int = go.layer;
// create our list if none exists
if(!objects[layer])
objects[layer] = new ArrayList();
var list:ArrayList = objects[layer];
// add if not present
if(!list.Contains(go))
list.Add(go);
// add to all
list = objects[-1];
if(!list.Contains(go))
list.Add(go);
}
/**
* Update when objects leave
*/
function OnTriggerExit(other:Collider)
{
if(!trackOtherTriggers && other.isTrigger)
return;
// is this collider in our ignore list?
for(var testIgnore:Collider in ignoreColliders)
if(testIgnore == other)
return;
var go:GameObject = other.gameObject;
var layer:int = go.layer;
// remove from all
var list:ArrayList = objects[-1];
list.Remove(go);
// Remove from layer’s list if it’s present
if(objects[layer])
{
list = objects[layer];
list.Remove(go);
}
}
/**
* Spew our list as an overlay in debug mode
*/
function OnGUI()
{
if(!Global.use.debug)
return;
var debug:String = “”;
for(var deictionaryEntry in objects)
{
var list:ArrayList = de.Value;
var layer:int = de.Key;
if(layer == -1)
continue;
debug += String.Format(“{0} : {1}
“, LayerMask.LayerToName(de.Key), list.Count);
}
var screen:Vector3 = Camera.main.WorldToScreenPoint(transform.position);
GUI.contentColor = Color.red;
GUI.Label(new Rect(screen.x, Screen.height - screen.y, 256, 128), debug);
}
An object destroyed inside of a trigger will not send OnTriggerExit events, so we must scrub our list of any null values before returning it.
Rather than poll this list continuously, our game logic script only checks for an update when things may have changed–when something enters or exits our trigger (the same trigger, as both the generic tracker script and our game logic script are on the same object). We separate scripts like this in order to keep the tracking script generic and reusable between projects. It is easy for our gameplay script to ask the tracker script for all of the objects in our BuildingPieces layer, for instance:
// should we do a calculation next update?
var isDirty:boolean = false;
// cache our tracker reference
private var tracker:TriggerTrackByLayer;
tracker = GetComponent(TriggerTrackByLayer);
/**
* Recalculate status every object
*/
function OnTriggerEnter()
{
isDirty = true;
}
function OnTriggerExit()
{
isDirty = true;
}
/**
* Check for dirty every FixedUpdate (after OnTrigger* calls)
*/
function FixedUpdate()
{
if(isDirty)
{
// do our game logic, ie:
var objectsInside = tracker.GetObjects(someLayerNumber);
}
// unset to prevent logic every frame
isDirty = false;
}
We use another variant that only tracks objects that match a certain LayerMask, which lets you avoid the overhead of tracking all objects in and out. The example project includes both scripts.
By the way, visualizing the status of your triggers via Gizmos is a very useful debugging tool. In the crane wars example you can draw box colliders like:
/**
* Debug display of our trigger state
*/
function OnDrawGizmos()
{
// set to whatever color you want to represent
Gizmos.color = Color.green
// we’re going to draw the gizmo in local space
Gizmos.matrix = transform.localToWorldMatrix;
// draw a box collider based on its size
var box:BoxCollider = GetComponent(BoxCollider);
Gizmos.DrawWireCube(box.center, box.size);
} |
|