- Home /
Question by
edve98 · Nov 21, 2014 at 08:37 PM ·
rotationraycastraycastingnot-working
Raycast is not working properly
Hi. Can anybody please check what is wrong in this script? I have been trying to fix it for 2 hours, and I just gave up.
using UnityEngine;
using System.Collections;
public class ai1 : MonoBehaviour {
public float spottingDistance = 1;
bool canSee;
bool alerted=true;
NavMeshAgent pathfinding;
GameObject player;
RaycastHit hitInfo;
void Start(){
pathfinding=GetComponent<NavMeshAgent>();
player = GameObject.FindGameObjectWithTag("Player");
}
void Update(){
Physics.Raycast(gameObject.transform.position, player.transform.position, out hitInfo, spottingDistance);
Debug.DrawRay(gameObject.transform.position, player.transform.position, Color.cyan);
if(hitInfo.transform.tag=="Player"){
canSee=true;
}
else{
canSee=false;
}
if(canSee){
Debug.Log("Enemy is shooting");
}
else if(alerted){
Debug.Log("Enemy is following");
pathfinding.SetDestination(player.transform.position);
}
}
}
This is what's wrong:
the hell.jpg
(45.2 kB)
Comment
Best Answer
Answer by richyrich · Nov 21, 2014 at 08:56 PM
The problem with your script is that although you are supplying two Vector3 variables, the second variable needs to be the direction, not the position that you are aiming for.
You need to create the direction.
Assuming the player is at the point of origin you would do this:
Vector3 dir = (gameObject.transform.position - player.transform.position).normalized;
Alternatively, if the gameObject is the origin, then reverse:
Vector3 dir = (player.transform.position - gameObject.transform.position).normalized;
Then
Physics.Raycast(gameObject.transform.position, dir, out hitInfo, spottingDistance);
Answer by Jamcount · Nov 21, 2014 at 08:52 PM
Have you tried making it in an if statement?
using UnityEngine;
using System.Collections;
public class ai1 : MonoBehaviour {
public float spottingDistance = 1;
bool canSee;
bool alerted=true;
NavMeshAgent pathfinding;
GameObject player;
RaycastHit hitInfo;
void Start(){
pathfinding=GetComponent<NavMeshAgent>();
player = GameObject.FindGameObjectWithTag("Player");
}
void Update(){
Debug.DrawRay(gameObject.transform.position, player.transform.position, Color.cyan);
if(Physics.Raycast(gameObject.transform.position, player.transform.position, out hitInfo, spottingDistance)){
if(hitInfo.transform.tag=="Player"){
canSee=true;
}
else{
canSee=false;
}
}
if(canSee){
Debug.Log("Enemy is shooting");
}
else if(alerted){
Debug.Log("Enemy is following");
pathfinding.SetDestination(player.transform.position);
}
}
}
I am not sure, but maybe it is because you just defined the position in Physics.Raycast ins$$anonymous$$d of a direction.
Physics.Raycast(gameObject.transform.position, player.transform.forward, out hitInfo, spottingDistance);