- Home /
AI Script walking on terrain
i was looked Some script in internet But all have problem while my enemy model Walk on Terrain..
i am triying use Character Controller and Character Motor But my character Turn Face To Y axiss if target point y axis value diffrent.
How i can write script ignore target y axis?
This is my code ..
using UnityEngine;
using System.Collections;
public class EnemyAI : MonoBehaviour {
public Transform target;
public int moveSpeed;
private Vector3 centerPoint;
private float distance;
private CharacterController character;
private Vector3 targetpoint ;
private Vector3 moveDirection;
private int gnp = 0;
void Awake(){
centerPoint = transform.position;
}
void Start () {
character = GetComponent<CharacterController>();
}
void Update () {
Walk();
}
void GotoTargetPoint(){
animation.CrossFade ("walk");
Vector3 moveDirection = targetpoint - transform.position;
if (moveDirection.magnitude < 2){
switch(gnp){
case 10:
gnp = 1;
Debug.Log("GNP " + gnp);
break;
case 20 :
gnp=0;
Debug.Log("GNP " + gnp);
break;
}
}else{
transform.LookAt(targetpoint);
character.Move(moveDirection.normalized * moveSpeed * Time.deltaTime);
}
}
void GetNewPoint(){
targetpoint = new Vector3(Random.Range(-13.0F, 13.0F), 0, Random.Range(-13.0F, 13.0F));
targetpoint = targetpoint + transform.position;
targetpoint.y = Terrain.activeTerrain.SampleHeight(targetpoint);
gnp = 10;
}
void Walk(){
if (gnp == 0){
GetNewPoint();
Debug.Log("GNP " + gnp);
}
if (gnp == 1 ){
targetpoint=centerPoint;
gnp = 20;
Debug.Log("GNP " + gnp);
}
GotoTargetPoint();
}
}
Answer by aldonaletto · Jan 29, 2012 at 09:07 PM
Copy targetpoint to a variable flatTarget, and copy the player's Y coordinate to it, so that flatTarget and the player will be at the same plane:
... void GotoTargetPoint(){
animation.CrossFade ("walk");
// create a "flat" targetpoint copying the player's y coordinate:
Vector3 flatTarget = targetpoint;
flatTarget.y = transform.position.y;
Vector3 moveDirection = flatTarget - transform.position; // use flatTarget instead of targetpoint
if (moveDirection.magnitude < 2){
switch(gnp){
case 10:
gnp = 1;
Debug.Log("GNP " + gnp);
break;
case 20 :
gnp=0;
Debug.Log("GNP " + gnp);
break;
}
}else{
transform.LookAt(flatTarget); // <- look at the flatTarget point
character.Move(moveDirection.normalized * moveSpeed * Time.deltaTime);
}
}
Your answer
Follow this Question
Related Questions
Change AI Follow Players 1 Answer
2 questions about Terrain(AI on terrain) 1 Answer
AI Script attached to Enemy and is Rotating around player 0 Answers
Fast Script Ai For mobile: Navmesh or A*? 1 Answer
C# Script Not Working? 2 Answers