playMaker

Author Topic: Find Closest - Now with an Ignore Owner option  (Read 2321 times)

Neural Echo

  • 1.2 Beta
  • Playmaker Newbie
  • *
  • Posts: 12
    • View Profile
Find Closest - Now with an Ignore Owner option
« on: April 06, 2011, 02:21:23 PM »
Here's a slightly modified version of the built-in Find Closest action that optionally allows the user to ignore the object that owns the FSM that contains this action.

To update the built-in action with this version, replace the code inside the Assets/PlayMaker/Actions/FindClosest.cs script with the code below.


Code: [Select]
// (c) Copyright HutongGames, LLC 2010-2011. All rights reserved.

using UnityEngine;

namespace HutongGames.PlayMaker.Actions
{
[ActionCategory(ActionCategory.GameObject)]
[Tooltip("Finds the closest object to the specified Game Object.\nOptionally filter by Tag and Visibility.")]
public class FindClosest : FsmStateAction
{
[RequiredField]
public FsmOwnerDefault gameObject;
[RequiredField]
[UIHint(UIHint.Tag)]
public FsmString withTag;
[Tooltip("If checked, ignores the object that owns this FSM.")]
public bool ignoreOwner;
public FsmBool mustBeVisible;
[UIHint(UIHint.Variable)]
public FsmGameObject storeObject;
[UIHint(UIHint.Variable)]
public FsmFloat storeDistance;
public bool everyFrame;


public override void Reset()
{
gameObject = null;
withTag = "Untagged";
mustBeVisible = false;
storeObject = null;
}

public override void OnEnter()
{
DoFindClosest();

if (!everyFrame)
Finish();
}

public override void OnUpdate()
{
DoFindClosest();
}

void DoFindClosest()
{
GameObject go = gameObject.OwnerOption == OwnerDefaultOption.UseOwner ? Owner : gameObject.GameObject.Value;

GameObject[] objects = GameObject.FindGameObjectsWithTag(withTag.Value);
GameObject closestObj = null;
var closestDist = Mathf.Infinity;

foreach (var obj in objects)
{
if (ignoreOwner && obj == Owner)
continue;

if (mustBeVisible.Value && !ActionHelpers.IsVisible(obj))
continue;

var dist = (go.transform.position - obj.transform.position).sqrMagnitude;
if (dist < closestDist)
{
closestDist = dist;
closestObj = obj;
}
}

storeObject.Value = closestObj;
storeDistance.Value = closestDist;
}
}
}

tobbeo

  • 1.2 Beta
  • Full Member
  • *
  • Posts: 186
    • View Profile
Re: Find Closest - Now with an Ignore Owner option
« Reply #1 on: April 06, 2011, 04:47:48 PM »
Nice! Will test this out. Thank you for sharing!