Object lerping forwards a set distance every 3 seconds.
I was having trouble making my object move forwards from its local position at set distance every 3 seconds. I'm trying to use a coroutine at the moment but I am new and am in need of some guidance. any help is appreciated.
public float moveSpeed = 3f;
private BoxCollider boxCollider;
public float maxDistance = 3f;
void Start()
{
boxCollider = GetComponent<BoxCollider>();
}
void Update()
{
checkingForwards();
}
void checkingForwards()
{
boxCollider.enabled = false;
RaycastHit hit;
Ray detectingRay = new Ray(transform.position, Vector3.forward);
if (Physics.Raycast(detectingRay, out hit, maxDistance))
Debug.Log("After if(Physics.Raycast(detectingRay, out hit, maxDistance))");
{
boxCollider.enabled = true;
if (hit.transform == null)
{
StartCoroutine(movingForwardsCoroutine());
}
}
}
IEnumerator movingForwardsCoroutine()
{
while (true)
{
Debug.Log("OnCoroutine: " + (int)Time.time);
transform.position = Vector3.Lerp(transform.localPosition, transform.forward, Time.deltaTime * moveSpeed);
yield return new WaitForSeconds(3f) ;
}
}
Comment
Best Answer
Answer by tsdavs · Dec 21, 2015 at 05:31 AM
Credit to @Cnc96 and @MysterySoftware
Thanks again!
http://forum.unity3d.com/threads/solved-random-wander-ai-using-navmesh.327950/
[code=CSharp]
using UnityEngine;
using System.Collections;
public class WanderingAI : MonoBehaviour {
public float wanderRadius;
public float wanderTimer;
private Transform target;
private NavMeshAgent agent;
private float timer;
// Use this for initialization
void OnEnable () {
agent = GetComponent<NavMeshAgent> ();
timer = wanderTimer;
}
// Update is called once per frame
void Update () {
timer += Time.deltaTime;
if (timer >= wanderTimer) {
Vector3 newPos = RandomNavSphere(transform.position, wanderRadius, -1);
agent.SetDestination(newPos);
timer = 0;
}
}
public static Vector3 RandomNavSphere(Vector3 origin, float dist, int layermask) {
Vector3 randDirection = Random.insideUnitSphere * dist;
randDirection += origin;
NavMeshHit navHit;
NavMesh.SamplePosition (randDirection, out navHit, dist, layermask);
return navHit.position;
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612053212im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Animation out of time with custom clock 0 Answers
Waitforseconds doesn't work outside Start(). 0 Answers
Lerp with Coroutine doesn't behave as expected 0 Answers
Unity Freezing after for loop 1 Answer
Crouch Lerp Coroutine Problems 0 Answers