- Home /
Linecast always returning true
I am trying to make a linecast to avoid my enemy to fall off the map and getting stuck on walls, if he detects an edge or wall, he flips and start moving the other way. The linecast to detect edges is doing just fine, however the linecast facing left (to detect walls), is always getting triggered and i dont know why, so the enemy just keeps flipping every frame.
public class Enemy1 : MonoBehaviour {
Rigidbody2D myBody;
Transform myTransf;
public LayerMask enemyMask;
float myWidth;
public float speed;
// Use this for initialization
void Start () {
myTransf = this.transform;
myBody = this.GetComponent<Rigidbody2D>();
myWidth = this.GetComponent<SpriteRenderer>().bounds.extents.x;
}
// Update is called once per frame
void FixedUpdate () {
//Checking if theres an edge or wall, if so, flip and move the other way.
Vector2 lineCastPos = myTransf.position - myTransf.right * myWidth;
Debug.DrawLine(lineCastPos, lineCastPos + Vector2.down);
bool isGrounded = Physics2D.Linecast(lineCastPos, lineCastPos + Vector2.down, enemyMask);
Debug.DrawLine(lineCastPos, lineCastPos - myTransf.right.toVector2() *0.1f);
bool isBlocked = Physics2D.Linecast(lineCastPos, lineCastPos - myTransf.right.toVector2() * 0.1f, enemyMask);
RaycastHit2D hit = Physics2D.Linecast(lineCastPos, lineCastPos - myTransf.right.toVector2());
if (!isGrounded || !isBlocked)
{
Vector3 currRot = myTransf.eulerAngles;
currRot.y += 180;
myTransf.eulerAngles = currRot;
Debug.Log("Ray Hit: " + hit.point);
}
//Always walking to the left
Vector2 myVel = myBody.velocity;
myVel.x = -myTransf.right.x * speed;
myBody.velocity = myVel;
}
}
The RayCastHit2D Log gives me the point 0,0.0,0 (highlighted in the red dot in my screenshot) and nothing is sitting there, only the main camera.
Answer by rd_mcn · May 10, 2018 at 03:43 AM
Hi,
Not sure if this may help but my Raycasts were initially hitting the game object that was originating the cast and therefore always returning a hit. I found this by checking the game object name of the collider that returns the hit. Hope this might help.
Hey, Thanks for the input, but I think I already discarded that option, before I created this post, I've found this page talking exactly about this issue ( https://stackoverflow.com/questions/38191659/unity-physics2d-raycast-always-returns-the-invoker-as-hit/38193001#38193001 ) I already tried both methods shown to prevent this issue. Plus as an indicator, the Debug.Log("Ray Hit: " + hit.point);
doesnt return the same position as the linecast invoker (in this case the position registered is 0.00, 0.00)