I’m looking for a way to randomly change the rotation of an object, but slowly over time. I’m trying to create a wander behavior for my game’s ai, and use this for the direction of travel. Any suggestions?
public var elapsed : float = 0.0;
public var orig : Vector3;
public var dir : float = 0.0;
public var dur: float = 0.0 ;
public var target_rotation : Vector3;
function PickNewRandomDir(){
orig = transform.eulerAngles;
//pick a direction
dir = Rand.Range(0.0, 360.0);
//pick a duration in seconds
dur = Rand.Range(0.0, 2.0);
target_rotation = new Vector3( orig.x, orig.y, dir); //where z is the randomized direction
}
function Start(){
PickNewRandomDir();
}
function Update(){
if(elapsed > dur){
elapsed = 0.0;
}
transform.eulerAngles = Vector3.Lerp(orig, target_rotation, dur/elapsed);
elapsed = elapsed + Time.deltaTime;
}
something like that should do what you wanted (untested code!),
the effect will be that you will be traveling in arcs of random size.
[/code]
Thanks for pointing me in the right direction. I adjusted your code slightly, this seems to work.
public var elapsed : float = 0.0;
public var orig : Vector3;
public var dir : float = 0.0;
public var dur: float = 0.0 ;
public var target_rotation : Vector3;
function PickNewRandomDir(){
//pick a direction
dir = Random.Range(0.0, 360.0);
//pick a duration in seconds
dur = Random.Range(0.0, 2.0);
target_rotation = new Vector3( orig.x, dir, orig.z); //where y is the randomized direction
}
function Start(){
// PickNewRandomDir();
}
function Update(){
if(elapsed > dur){
PickNewRandomDir();
elapsed = 0.0;
}
orig = transform.eulerAngles;
transform.eulerAngles = Vector3.Lerp(orig, target_rotation, Time.deltaTime * 1);
elapsed = elapsed + Time.deltaTime;
}
If I’m lerping between 2 eularAngles in 3 axes am I going to have gimbal issues? Any way to do something similar with quaternions?
Edit: Yeah, it works great in one axis, but not more than 1. I guess I could make a separate script for each axis and apply them to a hierarchy of game objects, but that seems kinda messy and bad for performance since there would be 3 lerps.