SpoocyCrep
SpoocyCrep

Reputation: 614

Rigidbody Mobs fall through ground while walking

I have a really odd issue, I created custom MOB AI in unity for my game (it has procedural generated voxel world so agents didn't work well). I use rigidbody on the mobs which I move around.

But I have this issue where mobs go inside the floor while moving (doesn't happen when standing) and when they stand, they teleport back up!. It's not animation, I disabled animations and it still happens.

here is how I move them:

   private void WalkToTarget()
{
    if (goal != Vector3.zero)
    {
        if (goal.y <= 5)
        {
            currentstatus = MOBSTATUS.STANDING;
            return;
        }
        var distance = Vector3.Distance(VoxelPlayPlayer.instance.transform.position, gameObject.transform.position);
        if (distance < 15)
        {
            goal = VoxelPlayPlayer.instance.transform.position;
            goal.y = VoxelPlayEnvironment.instance.GetHeight(goal);
        }
        if (distance < 5)
        {
            this.currentstatus = MOBSTATUS.ATTACKING;
        }
        //MOVEMENT HAPPENS HERE
        Vector3 direction = (goal - mobcontroller.transform.position).normalized*2f;
        if(mobcontroller.collisionFlags!=CollisionFlags.CollidedBelow)
        direction+= Vector3.down;
        mobcontroller.Move(direction * Time.fixedDeltaTime);
        RotateTowards(direction);
    }
}

Edit:

All code: https://pastebin.com/khCmfKGi

Upvotes: 0

Views: 80

Answers (2)

SpoocyCrep
SpoocyCrep

Reputation: 614

This problem happened when using Rigidbody and CharacterController on the mob. Removing Rigidbody from the mob solved this problem.

Upvotes: 0

Ruzihm
Ruzihm

Reputation: 20259

Part of your problem is that you are using CollisionFlags incorrectly.

Instead of this:

if(mobcontroller.collisionFlags!=CollisionFlags.CollidedBelow)

You need to do this

if(mobcontroller.collisionFlags & CollisionFlags.CollidedBelow)

Because you are trying to check if the mob is at least colliding below, not if the mob is only colliding below.

Even then, CharacterController.Move should not move you through colliders on its own.

I suspect that RotateTowards(direction) might be rotating the boundaries of mob's collider through the ground in some cases. To prevent that, I recommend creating a lookDirection that keeps the character rotation flat when you do your RotateTowards:

Vector3 direction = (goal - mobcontroller.transform.position).normalized*2f;
if(mobcontroller.collisionFlags & CollisionFlags.CollidedBelow)
    direction+= Vector3.down;
mobcontroller.Move(direction * Time.fixedDeltaTime);

Vector3 lookDirection = (goal - mobController.transform.position);
lookDirection.y = mobController.transform.y;
RotateTowards(lookDirection);

Upvotes: 1

Related Questions