Hello, in my 2D platformer enemies have simple AI: they walking from edge to edge of platform and chasing player if see him. They can’t jump so if creep chased player and fell to another platform, he need to get the new bounds to walking.
I’m wandering: what is the best way to get this bounds?
I’ve tried to make a series of downwarding Raycasts (that hits only platforms) at the right and left of object and if i detect change of height, it would mean that we find edge of platform or obstacle.
For some reason my implementation of this algorithm doesn’t work.
Here’s my implementation:
LayerMask lm = (1 << LayerMask.NameToLayer("Ground")); // Layer with platforms
RaycastHit2D hit = Physics2D.Raycast(transform.position,(-Vector2.up),lm);
// Getting collision with the platform beneath our creep
float platformy = hit.point.y; // Saving its height
// Now finding right bound
int i = 1;
while(Mathf.Abs (hit.point.y-platformy)<0.1f)
{
hit = Physics2D.Raycast(new Vector2(transform.position.x+(i*0.1f),(transform.position.y)),(-Vector2.up),lm);
i++;
}
wallLeft = hit.point.x-0.1f;
// Left one
hit = Physics2D.Raycast(new Vector2(transform.position.x,(transform.position.y+2f)),(-Vector2.up),lm);
i = 1;
while(Mathf.Abs (hit.point.y-platformy)<0.5f)
{
hit = Physics2D.Raycast(new Vector2(transform.position.x-(i*0.1f),(transform.position.y)),(-Vector2.up),lm);
i++;
}
wallRight = hit.point.x+0.1f;
(Sorry for bad English)