- Home /
Can See Target not working
Hi, all. I'm working on my AI, but I have a problem. I borrowed the CanSeeTarget() : boolean function from the tutorial, but It causes my enemy To rotate at a very fast rate. I was wondering if there was a way to fix this. All help is appreciated.
Here is my code:
enum s
{
Idle,
Pursuit,
Shooting
}
var Player : GameObject;
var walkSpeed : float;
var runSpeed : float;
var obstacleAvoidanceLevel : float;
var patrolChangesInterval : float;
var shootRange : float;
var noticeRange : float;
var showGizmosInEditor : boolean;
var gun : AIGun;
var Controller : CharacterController;
@HideInInspector
var state : s;
private var lastChange : float;
private var moveSpeed : float;
function Awake()
{
patrolChangesInterval += Random.Range(-1.5, 1.5);
moveSpeed = walkSpeed;
}
function Update()
{
Controller.Move(-Vector3.up * Time.deltaTime * 10);
Controller.Move(transform.forward * moveSpeed*Time.deltaTime);
if(Time.time > lastChange)
{
lastChange = Time.time + patrolChangesInterval;
ChangeDirection();
}
var hit : RaycastHit;
if(Physics.Raycast(transform.position, transform.forward, hit, obstacleAvoidanceLevel))
{
if(hit.collider.tag != "Player")
{
ChangeDirection();
}
}
var dist : float;
dist = Vector3.Distance(Player.transform.position, transform.position);
if(dist < noticeRange && dist > shootRange && CanSeeTarget())
{
state = s.Pursuit;
moveSpeed = runSpeed;
} else if(dist < shootRange && CanSeeTarget())
{
state = s.Shooting;
moveSpeed = 0;
} else {
state = s.Idle;
moveSpeed = walkSpeed;
}
if(state != s.Idle)
{
transform.LookAt(Player.transform);
if(state == s.Shooting)
{
gun.Shoot();
}
}
}
function ChangeDirection ()
{
transform.Rotate(Vector3(0, Random.Range(90, 270), 0));
}
function CanSeeTarget () : boolean
{
var hit : RaycastHit;
if (Physics.Linecast (transform.position, Player.transform.position, hit))
return hit.collider.gameObject == Player;
return false;
}
function OnDrawGizmosSelected ()
{
if(showGizmosInEditor)
{
Gizmos.color = Color.yellow;
Gizmos.DrawWireSphere(transform.position, noticeRange);
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(transform.position, shootRange);
} }
Answer by Anxo · Jun 14, 2011 at 11:37 AM
it does not look like there is a problem with your code. atleast not that I can tell. My best guess is that this is getting called.
if(Physics.Raycast(transform.position, transform.forward, hit, obstacleAvoidanceLevel))
{
if(hit.collider.tag != "Player")
{
ChangeDirection();
}
}
I would put a Debug.Log in it and see if that's being called when the enemy spins around, if so, you can use Debug.Log(hit.transform.name) to see what it is hitting. It might be hitting itself.
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
Can See Target Not Working 1 Answer
Switch Case for Basic AI.... 1 Answer
Coordinating multiple AI enemies 3 Answers
How to make basic AI in a 2d game? 4 Answers