- Home /
Checking name from hit from Raycast in array
I´m trying to check an array of obstacles on which the enemy AI shouldn´t be walking. Each step, I´m casting a Raycast to the left, front and right. If it hits something, it´s checking the name of the object the Raycast hit in the array. If it´s in that array, the enemy AI shouldn´t be walking there.
This is the code:
var obstacles = ["Border", "Boundary", "BoundaryFlame"];
var frontAvailable = true;
var leftAvailable = true;
var rightAvailable = true;
var hitFront: RaycastHit;
if (Physics.Raycast(transform.position, transform.position + transform.forward, hitFront, 1.5)) {
Debug.Log("I hit this in front: ");
Debug.Log(hitFront.collider.gameObject.name);
for (var i = 0; i < obstacles.length; i++)
{
if (obstacles[i].IndexOf(hitFront.collider.gameObject.name) > 0)
{
Debug.Log("Hit in front!");
frontAvailable = false;
}
}
}
var hitLeft: RaycastHit;
if (Physics.Raycast(transform.position, transform.position +- transform.right, hitLeft, 1.5)) {
Debug.Log("I hit this on my left: ");
Debug.Log(hitFront.collider.gameObject.name);
for (var j = 0; j < obstacles.length; j++)
{
if (obstacles[j].IndexOf(hitLeft.collider.gameObject.name) > 0)
{
Debug.Log("Hit in left!");
leftAvailable = false;
}
}
}
var hitRight: RaycastHit;
if (Physics.Raycast(transform.position, transform.position + transform.right, hitRight, 1.5)) {
Debug.Log("I hit this on my right: ");
Debug.Log(hitFront.collider.gameObject.name);
for (var k = 0; k < obstacles.length; k++)
{
if (obstacles[k].IndexOf(hitRight.collider.gameObject.name) > 0)
{
Debug.Log("Hit in right!");
rightAvailable = false;
}
}
}
The problem is, all 3 booleans stay true. Ingame, I see the AI walking random ways (into walls sometimes). That means the checking of gameobjects isn't working right.
The Debug.Log shows it sometimes hits Boundary(Clone). In that case, it should set the boolean to false. In the array of obstacles, I've placed Boundary, and the index of that name in Boundary(Clone) should be higher then 0? What am I missing?
Answer by Joetjah · Jan 25, 2013 at 08:35 PM
My if is looking for Boundary(clone) at the beginning of Boundary, rather than the other way around. I was looking for:
if (hitFront.collider.gameObject.name.IndexOf(obstacles[i]) >= 0)
Answer by Kwaung · Jan 25, 2013 at 06:56 PM
I think delete transform.position from the 2nd argument of the raycast function will help.
like this.
if (Physics.Raycast(transform.position, transform.forward, hitFront, 1.5)) {
Your answer
Follow this Question
Related Questions
Can someone help me fix my Javascript for Flickering Light? 6 Answers
Setting Scroll View Width GUILayout 1 Answer
Enemy AI With changing Player 0 Answers
Collisions not working when player stands still 1 Answer
How to make basic AI in a 2d game? 4 Answers