- Home /
This question was
closed Sep 06, 2015 at 07:40 PM by
legetic.
2d raycast enemy detection problem.
So i've been trying to solve this problem for about 2-3 days now and no matter how many guides i look at i cant seem to solve it... i am making a 2D game and am trying to use raycasting as the enemy's playerdetection. i have commented the code and tried to make it as clear as possible so i am hoping someone could check it out and that the code speaks for itself. I included the whole code so the bottom section is most likely not a part of the problem since it's been working. Thanks in advance! /C# Newbie
private Transform myTransform;//my (the enemy's)transform
public Transform target;//The player't transform
public int maxDistance;//detection distance
public int moveSpeed = 3;//movement speed
public int Direction;//direction of movement and sprite
void Awake(){
myTransform = transform;//init my transform
}
void Start () {
GameObject go = GameObject.FindGameObjectWithTag("Player");//init player
target = go.transform;//init player transform
maxDistance = 10;//init detectiondistance
}
void Update () {
RaycastHit hit;//init raycast hit to store info about the object that was hit
Debug.DrawRay(target.position, myTransform.position - target.position, Color.red); //debug ray to see the ray
Ray detectionRay = new Ray (target.position, myTransform.position - target.position);//the ray that will be used (Ray2D doesn't seem to work)
if (Physics.Raycast(detectionRay,out hit))//this is makes me kind of puzzled because it seems like im only asking if the ray is cast but idk.
{
Debug.Log(hit.collider.name+", "+hit.collider.tag);
Debug.Log("NOOOOOOOOOOHIT");//even this doesn't seem to show up in console. kept this her because it would be a first step to get this one working.
if (hit.collider.gameObject.name == "Player")//if the object that was hit goes by the name "Player" then:
{
Debug.Log("HIT");//write HIT
}
}
//everything under here seems to work fine and are most likely not a part of the problem. pasted them too just in case.
if (target.position.x > myTransform.position.x +1) {
Direction = 1;
} else if(target.position.x < myTransform.position.x -1){
Direction = -1;
}
if(Vector2.Distance(target.position, myTransform.position) < maxDistance){
//Move towards target
myTransform.position += myTransform.right * moveSpeed * Direction * Time.deltaTime;
}
gameObject.transform.localScale = new Vector2 (Direction, 1);
}
Comment
And yes i know the ray wont affect the enemy's movement as it currently is. Right now i simply want the ray to work and collide with stuff and in case it collides with the player i should get some sort of indication (debug message).