- Home /
Raycast on an AI Game object
I need to make a raycast from an enemy game object to detect how close it is to a terrain wall to be able to turn around and find another path, I have tried on my own already but I did not get good results. I was hoping someone would be able to help me make a script that can do this properly and be intergrated into my enemies AI code. Thank you!
Here is the enemies' AI code: using UnityEngine; using System.Collections;
[RequireComponent(typeof(CharacterController))]
public class AIScript : MonoBehaviour
{
Transform _player;
Transform _Raptor;
[SerializeField]
public float
_moveSpeed = 5.0f;
/*[SerializeField]
float
Distance = 0.0f;*/
[SerializeField]
public float
_gravity = 2.0f;
public float _yVelocity = 0.0f;
// Cached variables
CharacterController _controller;
protected Animator RaptorAnimator;
Transform _transform;
ChangeDirection _ChangeDirection;
//Movement variables;
float speed = 5f;
float gravity = 100f;
Vector3 moveDirection;
Vector3 _target;
float maxRotSpeed = 200.0f;
float minTime = 0.1f;
float _velocity;
bool change;
float range;
bool chase = false;
int RandomAnimation = 1;
int OldRandomAnimation = 0;
RaycastHit hit;
void Start()
{
_controller = GetComponent<CharacterController>();
_transform = GetComponent<Transform>();
RaptorAnimator = GetComponent<Animator> ();
GameObject playerGameObject = GameObject.FindGameObjectWithTag ("Player");
_player = playerGameObject.transform;
GameObject EnemyGameObject = GameObject.FindGameObjectWithTag ("Raptor");
_Raptor = EnemyGameObject.transform;
_ChangeDirection = GetComponentInChildren<ChangeDirection> ();
range = 2f;
_target = GetTarget();
InvokeRepeating("NewTarget", 0.01f, 2.0f);
}
void OnTriggerStay (Collider inrange)
{
if (inrange.tag == "WallorTree") {
Debug.Log ("Touching");
//wallhit = true;
} else {
//wallhit = false;
}
if (inrange.tag == "Player"&& _controller.isGrounded==false)
{
//Debug.Log ("Not Touching");
RaptorAnimator.SetBool ("RunDistance", true);
_moveSpeed = 25;
chase = true;
}
}
void OnTriggerExit(Collider outofrange)
{
if (outofrange.tag == "Player"&& _controller.isGrounded==false)
{
RaptorAnimator.SetBool ("RunDistance", false);
_moveSpeed = 5;
chase = false;
}
}
void Update()
{
if (_ChangeDirection.wallhit != false) {
//NewTarget ();
//if(hit.distance==100){
//print("There is something in front of the object!");
//}
Debug.Log("IM HITTING A WALL");
_Raptor.transform.Rotate (0,180,0);
//_ChangeDirection.wallhit = false;
} else {
// _ChangeDirection.wallhit = true;
}
if(chase == false){
if (change) _target = GetTarget();
if (Vector3.Distance(_transform.position, _target) > range )
{
Move();
RaptorAnimator.SetBool ("Idle", false);
}else{
RaptorAnimator.SetBool ("Idle", true);
RandomAnimation = Random.Range(0, 10);
// RaptorAnimator.SetBool ("Animation Running", true);
if(RandomAnimation != OldRandomAnimation){
RaptorAnimator.SetInteger ("RandomAnimationIdle", RandomAnimation);
}else{
RandomAnimation = Random.Range(0, 10);
}
}
}else{
RaptorAnimator.SetBool ("Idle", false);
Vector3 direction = _player.position - transform.position;
direction.Normalize ();
Vector3 velocity = direction * _moveSpeed;
if (!_controller.isGrounded) {
_yVelocity -= _gravity;
}
velocity.y = _yVelocity;
direction.y = 0;
transform.rotation = Quaternion.LookRotation (direction);
_controller.Move (velocity * Time.deltaTime);
}
}
void Move()
{
// Movement
moveDirection = _transform.forward;
moveDirection *= speed;
moveDirection.y -= gravity * Time.deltaTime;
_controller.Move(moveDirection * Time.deltaTime);
//Rotation
var newRotation = Quaternion.LookRotation(_target - _transform.position).eulerAngles;
var angles = _transform.rotation.eulerAngles;
_transform.rotation = Quaternion.Euler(angles.x,
Mathf.SmoothDampAngle(angles.y, newRotation.y, ref _velocity, minTime, maxRotSpeed),
angles.z);
}
Vector3 GetTarget()
{
return new Vector3(Random.Range(0, 300), 0, Random.Range(0, 300));
}
void NewTarget()
{
int choice = Random.Range(0, 3);
switch (choice)
{
case 0:
change = true;
break;
case 1:
change = false;
break;
case 2:
_target = transform.position;
break;
}
}
}
Answer by PippyLongbeard · May 22, 2014 at 12:51 AM
'Physics.Raycast' can be used for this.
Physics.Raycast(_Raptor.position, _Raptor.transform.forward, rayDistance);
This would return true if the raycast hits something. 'rayDistance' would be how close the raptor is going to be before it notices the wall. You'll have to play around with that. However, this would detect anything in front of the raptor. To detect only the wall, you can use a RaycastHit.
RaycastHit hit;
if(Physics.Raycast(_Raptor.position, _Raptor.transform.forward, rayDistance, out hit))
{
if(hit.transform.name=="Wall")
{
//Do whatever
}
}
That's an example on how you'd do that. You don't necessarily need to search for the name. It can be a tag, property, etc. Hope this helps!
Your answer
Follow this Question
Related Questions
How to RayCast a triangular field of view for my autonomous moving agent 4 Answers
How to Check for Enemie in Front? Raycast is not Enough! 2 Answers
enemy Raycast cone detection 0 Answers
Slant Physics Raycast Implementation 0 Answers
Detect obstacle on path 0 Answers