I’m trying to make an object in my scene move around freely. So I want to randomise when it will switch directions and speeds. But I’m having trouble with the code. I don’t know how to randomize the code. And I would also like to have the object take random pauses and just stand still. How do I modify this code to do all that I want to do?
var stuff : Transform; // Needs rigidbody attached with a collider
var vel : Vector3; // Holds the random velocity
var switchDirection : float = 3;
var curTime : float = 0;
var RandomVariable : int;
RandomVariable = Random.Range (0,20);
function SetVel()
{
if (Random.value > .5) {
vel.x = 10 * 10 * Random.value;
}
else {
vel.x = -10 * 10 * Random.value;
}
if (Random.value > .5) {
vel.z = 10 * 10 * Random.value;
}
else {
vel.z = -10 * 10 * Random.value;
}
}
function Update()
{
if (curTime < switchDirection ) {
curTime += 1 * Time.deltaTime;
}
else {
SetVel();
if (RandomVariable > .5) {
switchDirection += Random.value;
}
else {
switchDirection -= Random.value;
}
if (switchDirection < 1) {
switchDirection = 1 + Random.value;
}
curTime = 0;
}
}
function FixedUpdate()
{
stuff.rigidbody.velocity = vel;
}
Nvrmind, fixed the problem. But how do I get the object to make random pauses in its movement?
Or more clearly put, make it pause and rotate its trajectory angle when it’s changing directions. (ie. Walk, pause/rotate,walk,etc.)
Pretty simple, just add it to your newVelocity statement. check a Random value against the amount you want it to stay and if it is, change the velocity to zero and set the next time to wait some.
Thanks a lot BigMisterB!
Also, it only changes directions/speed every five seconds or so. How do I make that number more varied?
I know, I’m asking quite a lot.
I’m sorry haha. I’ve been coding in Game Maker Language(GML) for years now and have just started on Unity so it’s a little confusing.
This code I’m trying to work on is basically an NPC movement script. How do I make them face the ovbject they are moving while have them rotate to the desired direction instead of immediate facing?
No joke haha. It’s kind of emberrassing. I’m a modeler, though. Not much of a programmer
ALSO (i know, right) This last thing and I shall most likely be happy. How do I smooth out the angling? When the object switches directions, it snaps ita angle towards that direction. How do I make it gently ease from direction A to direction B?