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);
}
}
}