RaycastHit2D works for one side but not the other

I must have a misunderstanding as to how RaycastHit2D works, and would appreciate some help.

This script is suppose to change an the enemy’s direction when the right or left collider == null. However, currently it only works corrently for the leftHit collider; the rightHit collider won’t work at first but will work when it hits the end of a slope, for some reason.

Here’s a gif of what’s happening (sorry, takes a few seconds to get going): Imgur: The magic of the Internet

I just want to keep the enemy moving left and right on a platform.

Thanks. How do I format the script text?

public class SimpleEnemy : MonoBehaviour
{

bool facingRight = false;

void Update()
{
var lineMinX = transform.collider2D.bounds.min.x;
var lineMinY = transform.collider2D.bounds.min.y;

var lineMaxX = transform.collider2D.bounds.max.x;
var lineMaxY = transform.collider2D.bounds.max.y-transform.collider2D.bounds.size.y;

RaycastHit2D leftHit = Physics2D.Raycast(new Vector2(lineMinX, lineMinY), -Vector2.up);
RaycastHit2D rightHit = Physics2D.Raycast(new Vector2(lineMaxX, lineMaxY), -Vector2.up);

//detect edge of platform
if (leftHit.collider == null)
{
facingRight = true;
Debug.Log(“facingRightFalse”);
}

if (rightHit.collider == null)
{
facingRight = false;
Debug.Log(“facingRightTrue”);
}

//apply change
if (facingRight == true)
{
rigidbody2D.velocity = new Vector2(2, rigidbody2D.velocity.y);
}
else
{
rigidbody2D.velocity = new Vector2(-2, rigidbody2D.velocity.y);
}
}
}

It’s actually not what you think - the problem is you’re not limiting the raycast distance, the third parameter that you’ve left at the default of Infinity. The only reason the one on the left works is because you happen to have no platform below the current platform for the raycast to hit. That’s also the reason why it works on the right side only after you’ve fallen down: again because there’s no platform below.

So just set a distance of a couple of units (2-4) and you should be good to go.

You also probably want both raycasts to begin at lineMaxY so they start at the toes - otherwise you’ll get inconsistent results.

1 Like

Thanks mate that worked!

1 Like