- Home /
Raycast moving and if null statements
So i'm fiddling around with a simple Boss AI for my 2D game, and i want the boss to first strafe around left and right, which works fine. Then after a certain amount of time i want it to move up if there is not something in the way, which i decide with the help of a layermask and a raycast. But this doesn't seem to work. Heres the code (i tried to put comments for further explanation):
void Awake()
{
startingPosY = transform.position.y;
endPosY = startingPosY + unitsToMoveY;
}
void FixedUpdate()
{
if(Time.time < 2)
{
MoveLR(); //moves left and right within a certain amount of units
Chase (); //chases the player left or right via raycasts
}
if(Time.time > 2)
{
MoveUp(); //this is the buggy code
Shoot (); //shoots whatever the player is left or right
}
}
void MoveUp()
{
Vector3 up = transform.TransformDirection (Vector3.up); //vector3 up
RaycastHit2D hitUp = Physics2D.Raycast (transform.position, up, 5, HitTheBox ); //the raycast that hits up to a box
Debug.DrawRay(transform.position, up, Color.red );
if(hitUp != null) //if the ray isnt null, move right, ie, if it hits something, move to the right
{
transform.position += Vector3.right * bossSpeed;
}
else if(hitUp == null) //then when the ray doesnt hit the box anymore, i want it to move up, but it doesnt work
{
MoveUpToBox();
}
}
void MoveUpToBox()
{
if(_moveUp)
{
transform.position += Vector3.up * bossSpeed;
}
if(transform.position.y >= endPosY)
{
_moveUp = false;
}
}
And my question is, how do i make it work so that, when the ray stops hitting the box above it, it starts moving up? any suggestions? thx in advance
Comment
I made it work, i simply forgot to add .collider to hit so it looks like this = if(hitUp.collider != null)