All of the examples I have seen thus far for moving an object relates directly to the user of the application being in control. What If I wanted to move an object controlled by some sort of AI(such as a monster)? How would I go about doing that? I’m having trouble since I can’t seem to find an appropriate example of it being done.
2 Answers
2You can set fixed values instead of using Input.GetAxis - this function return -1 to +1, so any value in this range will do the same as a constant Input.GetAxis. But this has a problem: your character will walk forever, eventually falling from the terrain edge somewhere in time. To avoid this, you must change its direction at intervals. There are several tricks available - doing random rotations at certain intervals is easy to implement. That’s a script like yours, but changing to random directions at some fixed interval:
var speed: float = 3;
var rotRange: float = 45; // random angle will be between -rotRange and rotRange
var timeToChange: float = 5; // change direction each timeToChange seconds
private var timer: float = 0; // start change timer
function Update(){
var controller : CharacterController = GetComponent(CharacterController);
timer = timer - Time.deltaTime; // decrements timer counter
if (timer<=0){
transform.Rotate(0, Random.Range(-rotRange, rotRange), 0);
timer = timeToChange;
}
controller.Move(transform.forward * speed * Time.deltaTime);
}
There are several ways to implement AI.
One of the simplest way to do so is to create an array of Vector3’s that determine the AI’s path. So if you wanted a monster to walk around your map, setup the waypoints as Vector3’s, and make your monster move towards each one in succession.
For enemy detection, you can make your monster do a Raycast, looking for the player, and change the monsters state to attack or perhaps flee if its health is below a certain level.
I’d suggest first doing the Unity FPS tutorial. There is a section in there on how to implement enemy AI.
I wasn't really looking for a way to implement AI, what I needed is an example of moving an object that is not controlled by player input.
– TheEmeralDreamer
what i mean is this :
– TheEmeralDreamerfunction MovePlayer() { var controller : CharacterController = GetComponent(CharacterController); transform.Rotate(0, Input.GetAxis("Horizontal") * rotateSpeed, 0); var forward=transform.TransformDirection(Vector3.forward); var curSpeed= speed *Input.GetAxis("Vertical"); controller.SimpleMove(forward * curSpeed);This is code to move something based on Human input, and that's what confuses me. Instead of accepting input from a controller or keyboard, how would i direct an object to move itself.transform.Rotate(0, ?????? * rotateSpeed, 0);