- Home /
How to use SimpleMove randomly move an NPC?
[2D platform game, new to Unity and C#]
I've learned how to use SimpleMove to control my character with arrow keys. I've heard that you can also use it for objects that move around a level.
In my case, I need my object to move around randomly on the X plane. I've tried modifying the code below to detach SimpleMove from input keys, but I couldn't make it work. I've posted the original code that I'm using for my input-controlled character. Does anyone know how to transform this code into something I can use for an NPC who wanders around randomly?
Thanks!
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(CharacterController))]
public class Movement : MonoBehaviour {
public float speed = 3.0F;
public int creature_type = 0;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
CharacterController controller = GetComponent<CharacterController>();
Vector3 forward = transform.TransformDirection(Vector3.right);
float curSpeed = speed * Input.GetAxis("Horizontal");
controller.SimpleMove(forward * curSpeed);
}
}
Answer by fafase · Mar 30, 2012 at 06:00 AM
Your solution would be to place an array of waypoints that the NPC will use as target.
It would not move randomly on the map, but let's say you have 4 waypoints you can always choose the next one randomly giving the idea that the NPC is moving with no purpose.
1/ create the waypoint array, they could be simple empty game object with a transform.
2/ use a random function to define the index of the array and make the coresponding waypoint the target.
3/ use transform.LookAt(target); to make the NPC look at the target and make move towards it
4/check the distance with the target so that when it reaches you get back to part 2. And so on.
Later you can add a function that checks the distance with the player so that if your player gets within a range the NPC drops its routine and chases you the same way. And lastly if the range gets too big, your guy gets back to its routine.
!!! This is ok for starting and if you do not have a lot of object in your environment. In that case you would have to use a simple pathfinding algorithm or some kind of raycast checking if something in the way.