playMaker  Author Topic: Get random point in transform  (Read 2140 times)

speedything

• Playmaker Newbie
• • Posts: 13 Get random point in transform
« on: January 06, 2012, 08:20:10 PM »
Following my theme of randomness, here's a new action. It allows you to find a random point within a transform, or at least it will for cubes and rectangles. Not so effective for circular objects...

Code: [Select]
using UnityEngine;

namespace HutongGames.PlayMaker.Actions

{
[ActionCategory(ActionCategory.Transform)]
[Tooltip("Gets a Random Position in a Transform")]
public class GetRandomPositionInTransform : FsmStateAction
{
[RequiredField]
public FsmOwnerDefault gameObject;
[UIHint(UIHint.Variable)]
public FsmVector3 vector;
[UIHint(UIHint.Variable)]
public FsmFloat x;
[UIHint(UIHint.Variable)]
public FsmFloat y;
[UIHint(UIHint.Variable)]
public FsmFloat z;
public Space space;
public bool everyFrame;

public override void Reset()
{
gameObject = null;
vector = null;
x = null;
y = null;
z = null;
space = Space.World;
everyFrame = false;
}

public override void OnEnter()
{
DoGetRandomPositionInTransform();

if (!everyFrame)
Finish();
}

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

void DoGetRandomPositionInTransform()
{
GameObject go = Fsm.GetOwnerDefaultTarget(gameObject);
if (go == null) return;

Vector3 position;

if (space == Space.World)
{

position = go.transform.position;
}

else
{
position = go.transform.localPosition;
}

Vector3 scale;

if (space == Space.World)

{
scale = go.transform.lossyScale;
}

else

{
scale = go.transform.localScale;
}

var halfX = scale.x/2f;
var halfY = scale.y/2f;
var halfZ = scale.z/2f;

var randomX = Random.Range(-halfX, halfX);
var randomY = Random.Range(-halfY, halfY);
var randomZ = Random.Range(-halfZ, halfZ);

x.Value = position.x + randomX;
y.Value = position.y + randomY;
z.Value = position.z + randomZ;

Vector3 randomVector3;

randomVector3.x = x.Value;
randomVector3.y = y.Value;
randomVector3.z = z.Value;

vector.Value = randomVector3;

}
}
}

Personally I'm using this to give my AI people a variety of destinations within an area that I can simply bound by creating a rectangle object.

Bye,

« Last Edit: January 06, 2012, 08:24:58 PM by speedything »