So I’m looking to make my model wander around once at a certain speed in to a random waypoint.
I was thinking. And thank you if you reply!! I’ve been looking for a solution online and haven’t found one.
function Start ()
{
InvokeRepeating("Tick", 300, 300); //Every 3mins run "tick"
}
function Tick ()
{
//waypoint to a random location. Moving position at certain speed
}
Pirs01
August 20, 2014, 1:38am
2
Posting code: Using code tags properly - Unity Engine - Unity Discussions
Cleaner approach would be to invoke your movement code in FixedUpdate method: Unity - Scripting API: MonoBehaviour.FixedUpdate()
Assuming your object has a Rigidbody component you should move it around by applying force to it: Unity - Scripting API: Rigidbody.AddForce
EDIT: For getting random values for your movement checkout Random class: Unity - Scripting API: Random
Tried everything and nothing seems to work.
Make a blank scene, drop a cube in so you can see it in the camera, and add this little script to the cube itself.
using UnityEngine;
using System.Collections;
public class RunToRandomPoint : MonoBehaviour
{
Vector3 targetPos;
float MovementSpeed = 5.0f;
float CloseEnough = 0.5f;
IEnumerator Start ()
{
targetPos = transform.position;
while(true)
{
// do not move
yield return new WaitForSeconds( 2.0f);
// choose new location
targetPos = new Vector3( Random.Range ( -10, 10), Random.Range( -5, 5));
// wait until we arrive
while( (transform.position - targetPos).magnitude > CloseEnough)
{
yield return new WaitForSeconds(0.0f);
}
}
}
void Update ()
{
// have we arrived?
if ((transform.position - targetPos).magnitude > CloseEnough)
{
// nope, turn to and go
transform.LookAt( targetPos);
transform.position += (targetPos - transform.position).normalized *
MovementSpeed * Time.deltaTime;
}
}
}