Physics.Raycast Enemy AI Problem

Hi,
I am doing enemy AI. I want to check that if player comes in the range of enemy then enemy will attack on it. I am using the following code but it is not working exactly. Can any one help me regarding this? Waiting anxiouly for any solution;

var Player : GameObject;
var check3 : boolean = Physics.Raycast (transform.position,transform.TransformDirection(Player.transform.position),hit3,1000);

if (check3 )
{
if (hit3.collider.name == “PlayerTank”)
{
print(“Player is in range of enemy”);
}
}

I’m not 100% sure what you are trying to do here, but I’m sure it’s not doing what you intend. TransformDirection() transforms a direction vector from local to world coords – passing it a world position will do nothing, or nothing useful anyway.

If you just want to know if the player is within 1000 units of an enemy, this is a much better way to do it:

if ((Player.transform.position - transform.position).magnitude <= 1000)
{
     // Player is in range
}

A small optimization (magnitude is expensive) would be:

if ((Player.transform.position - transform.position).sqrMagnitude <= (1000 * 1000))
{
     // Player is in range
}

This YouTube channel includes AI tutorials with js and c#

regards

if you have to do raycasting use this instead of the transform.TransformDirection.

var player : Transform;
var hit : RaycastHit

function Update () {
var playerRelativePos = player.position - transform.position;  // find the player
// relative to the enemy

if(Physics.Raycast(transform.position, playerRelativePos, hit, 1000)) {
// send a ray from the enemy in the direction we just figured out.

     if(hit.transform == player) {
          print("Player is in range of the enemy");
     }
}

Hi, I am doing a more complex system, basically it’s a creature type script that detects any other creature type that is in range.(Collision, Rigidbody required).

It will only attack if the type is Passive or Player, and itself is Agressive.
Make sure you set the detectionRadius to something other than 0, and I set all my detections to another Mask Layer just for detections.

And when it triggers, the attacking for the creature will become true.

Hope it helps.

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class TargetType : MonoBehaviour {
	
	
	
	
	// Carnivores -> meat eaters.
	// Herbivore -> eat plants
	// Omnivore -> eat meat and plants.	
	//public enum TargetCreatureType{Herbivore, Omnivore, Carnivore}
		
	// attacks
	// doesn't attack
	public enum TargetModeType{Player,Aggressive, Passive};
		
	public TargetModeType targetState = TargetModeType.None;
	
	public float DetectionRadius = 0;	
	// the self trigger volume
	public Collider handleMe;
	
	[System.NonSerialized()]
	public GameObject targetedObject;
	public bool attacking = false;	
	
	private TargetType ScriptType;
	
	public LayerMask VolumeLayer;
	
	public Collider[] colliders; 
	
	public float AttackingTime = 5;
	/////////////////////////////////////////
	// this system holds property for our collisions
	public class DetectionSystem : System.Object {
		
		public GameObject GO;
		public float Timer;
	}
	//////////////////
	// we add all our detectionSystem code into our arraylist and then compare and
	// find out which timer has expired
	public List<DetectionSystem> detectionList = new List<DetectionSystem>(); 

	public List<DetectionSystem> removeList = new List<DetectionSystem>();
	
	void Start()
	{
		handleMe = this.collider;
			//rigidbody.isKinematic = true;
			//rigidbody.detectCollisions = false;
			//handleMe = this.collider;
	}
	
	
	void Update()
	{		
		CheckBoundingVolume();
	}
	
	
	///////////////////////////////
	// check all surrounding colliders
	// update our object list
	// and its timer.
	////////////////////////////////	
	public void CheckBoundingVolume()
	{
		colliders = Physics.OverlapSphere(transform.position, DetectionRadius, VolumeLayer.value);
		
		////////////////////////////
		// add our colliders
		/////////////////////////////
		for(int i = 0; i<colliders.Length; i++) 
		{ 
			if(colliders[i] != handleMe)
			{			
				
				DetectionSystem detectionSystem = new DetectionSystem(); 
				detectionSystem.GO = colliders[i].gameObject;
				detectionSystem.Timer = 0;
	
				
				if(detectionList.Contains(detectionSystem))
				{}
				else{
					detectionList.Add(detectionSystem);
				}
			}
		} 
		
		///////////////////////////////////////////////////////////
		// remove our colliders
		// * check our List Capacity
		// * check go through our list
		// * set remove = true
		// * current Object exist in list set erase to false
		// * else set erase to true and erase.
		//////////////////////////////////////////////////////////
		
		if(detectionList.Count > 0)
		{
			foreach(DetectionSystem detection in detectionList )		
			{
				int erase = 1;
				for(int i = 0;  i< colliders.Length; i++)
				{					
					if(detection.GO == colliders[i].gameObject)
					{
						erase = 0;
					}
				}
				if(erase == 1)
				{
					removeList.Add(detection);					
				}
				
					
			}
		}
		
		if(removeList.Count > 0)
		{
			foreach(DetectionSystem detection in removeList)
			{
				detectionList.Remove(detection);				
			}
		}
		
		removeList.Clear();
	
		
		/////////////////////
		// update and delete
		/////////////////////
		if(detectionList.Count> 0)
		{
			foreach(DetectionSystem detection in detectionList)
			{
				detection.Timer += Time.deltaTime;
				//Debug.Log("Timer: " + detection.Timer + " " + detection.GO);
				
				if(detection.Timer >= AttackingTime)
				{
					// check to see their aggressiness
					
					ScriptType = (TargetType)detection.GO.GetComponent("TargetType");
					if(targetState == TargetModeType.Aggressive )
					{
						if(ScriptType.targetState == TargetModeType.Passive || ScriptType.targetState == TargetModeType.Player)
						{
							
		
							//detection.Timer = 0;
							attacking = true;							
							targetedObject = detection.GO;
							detectionList.Clear();
							
						}
					}
				}
			}
			
		}
		
		/////////
		// clear our list if our object is set to attacking
		
	
		
			

		
	}