For example if he is instantiated and falls on a floor which holds the layer named platform then he should calculate the limits to which extent he would move over that floor
public class Temp : MonoBehaviour {
struct Values
{
public GameObject LandingPlatform ;
public BoxCollider2D _boxCollider ;
public Bounds platformBound ;
public Vector3 LeftLimit ;
public Vector3 RightLimit ;
}
//-------------- Just for checking the wether the limits are working correctly
public Vector3 LeftLimit ;
public Vector3 RightLimit ;
//--------------
Values _values ;
RaycastHit2D _raycastHit ;
RaycastHit2D previousRaycastHit ;
public LayerMask platform ;
void Update ()
{
EnemyPlatformLimit();
LeftLimit = _values.LeftLimit ;
RightLimit = _values.RightLimit ;
}
void EnemyPlatformLimit()
{
DrawRay (gameObject.transform.position , -Vector2.up * 1.5f , Color.yellow ) ;
previousRaycastHit = _raycastHit ;
_raycastHit = Physics2D.Raycast ( gameObject.transform.position , -Vector2.up , 1.5f , platform) ;
if(_raycastHit && _raycastHit != previousRaycastHit)
{
_values.LandingPlatform = _raycastHit.transform.gameObject ;
_values._boxCollider = _values.LandingPlatform.GetComponent<BoxCollider2D>() ;
_values.platformBound = _values._boxCollider.bounds ;
_values.LeftLimit = _values.platformBound.center - _values.platformBound.extents ;
_values.RightLimit = _values.platformBound.center + _values.platformBound.extents ;
}
if ((_raycastHit))
{
//both statements execute even though technically they should not
if(transform.position.x > _values.RightLimit.x)
{
Debug.Log(transform.position.x) ;
ChangeDirection();
}
else if (transform.position.x < _values.LeftLimit.x)
{
Debug.Log(transform.position.x) ;
ChangeDirection();
}
}
}
void DrawRay(Vector3 origin , Vector2 dir , Color color)
{
Debug.DrawRay(origin , dir , color ) ;
}
void ChangeDirection()
{}
}