- Home /
Question by
TheChanger · Mar 01, 2018 at 05:28 PM ·
androidmovementai
How do I make my AI move and follow me once I am close enough.
I have recently watched two YouTube tutorials on AI and as I am a beginner with C# I do not understand where it has gone wrong. Can anyone fix the scripting errors it might be due to the conflicts with the two tutorials and how I packed both into one script and did some of my own programming. Thanks. Here is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class EnemyController : MonoBehaviour {
public float fpsTargetDistance;
public float enemyLookDistance;
public float attackDistance;
public float enemyMovementSpeed;
public float damping;
public Transform fpsTarget;
Rigidbody theRigidbody;
Renderer myRender;
public float AIWallDistance;
public Transform AIWall;
public Transform DeathZone;
public LayerMask whatIsWall;
public float MaxDistanceFromWall;
public Vector3 moveDir;
void Start(){
myRender = GetComponent<Renderer> ();
theRigidbody = GetComponent<Rigidbody> ();
moveDir = ChooseDirection ();
transform.rotation = Quaternion.LookRotation (moveDir);
}
Vector3 ChooseDirection()
{
System.Random ran = new System.Random ();
int i = ran.Next (0, 3);
Vector3 temp = new Vector3 ();
if(i==0){
temp = transform.forward;
}
else if(i==1){
temp = -transform.forward;
}
else if(i==2){
temp = transform.right;
}
else if(i==3){
temp = -transform.right;
}
return temp;
}
void Update()
{
theRigidbody.velocity = moveDir * enemyMovementSpeed;
if(Physics.Raycast(transform.position, transform.forward,MaxDistanceFromWall))
{
moveDir = ChooseDirection ();
transform.rotation = Quaternion.LookRotation (moveDir);
}
}
void FixedUpdate(){
theRigidbody.AddForce (transform.forward * enemyMovementSpeed);
fpsTargetDistance = Vector3.Distance (fpsTarget.position, transform.position);
if (fpsTargetDistance < enemyLookDistance) {
myRender.material.color = Color.yellow;
LookAtPlayer ();
theRigidbody.AddForce (transform.forward * enemyMovementSpeed);
}
if (fpsTargetDistance < attackDistance) {
attack ();
}
}
void LookAtPlayer(){
Quaternion rotation = Quaternion.LookRotation(fpsTarget.position-transform.position);
transform.rotation = Quaternion.Slerp (transform.rotation,rotation, Time.deltaTime*damping);
}
void attack(){
theRigidbody.AddForce (transform.forward * enemyMovementSpeed);
}
}
Comment
Why don't you use a Nav$$anonymous$$esh? Or if you are in 2D "A* pathfinding project
Your answer
Follow this Question
Related Questions
How can I move player sideways by dragging with mouse or with mobile device when pressed down? 0 Answers
How to return an enemy to its original location after losing aggro? 2 Answers
Ball control (pong) 1 Answer
Grid Based Movement System AI freezing? 1 Answer
What am I doing wrong with my AI? 1 Answer