Search code examples
c#unity-game-engine3dgame-physics

Unity 3D bot not correctly following player


I have two 3D rigidbody robots with box colliders in my scene. Here is my script on one of them to follow the other (without rotation) and push it:

public class BotFollowSwerve : MonoBehaviour
{
    public Transform target;
    public float force = 10f;

    private Rigidbody rb;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    void FixedUpdate()
    {
        Vector3 targetDirection = (target.position - transform.position).normalized;

        rb.AddForce(targetDirection * force, ForceMode.Force);
    }
}

The other robot is controlled by the player and can rotate and move. The issue is when the player faces away from the follower robot, the follower just lines itself up about 2 robot lengths away from the player robot and starts vibrating/moving in circles in place. If i move the player robot without rotating it - the follower follows with it, but keeps its distance. If i rotate back toward the follower, its normal following and bashing starts again.

I tried to to see if the targetDirection was ending up at zero, and thus the robot wouldn't move besides occasional fluctuations in the values. But that didn't seem to result in anything.


Solution

  • I would recommend you to use Navmesh as its really easy to setup for AI and does most of the job for you. enter link description here