ive figured out how to make an object move towards another with this code however i cant figure out how to make it move at a random speed.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveTowards : MonoBehaviour
{
public float speed = 3;
public Transform target;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
float step = speed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, target.position, step);
}
}
speed = Random.Range(min, max);
Random.Range Returns a random float within [minInclusive…maxInclusive] (range is inclusive).
step = Random.Range(min, max) * Time.deltaTime;
//is a float so remember use f after the value with comma or not: (1f, 10.0f)
follow the other answers, if you want speed change along the way, you can add the following coroutine, it will randomize the speed every two seconds.
void Start()
{
StartCoroutine(Speedrandomizer());
}
IENumerator Speedrandomizer()
{
while(true)
{
speed = Random.Range(minFloatValue, maxFloatvalue);
yield return new WaitForSeconds(2f);
}
}
otherwise, you can add it to Start()