- Home /
How to stop enemy AI from vibrating when tracking y component
When my AI tracks my balls y component and moves to the same y component, it starts to vibrate as it gets closer, even if the y component is exactly the same, flicking between going up 7 and down -7. The code for it looks like this
#endregion
#region Inspector Variables
[SerializeField] private float moveSpeed;
[SerializeField] private Vector2 ballPos;
[SerializeField] private GameObject ballRef;
#endregion
#region Private Variable
private float yInput;
#endregion
#region Components
Rigidbody2D rb;
#endregion
private void Start()
{
rb = GetComponent<Rigidbody2D>();
} //Onstartup executes
private void FixedUpdate()
{
UpdateBallPos();
MoveAI();
}
#region Methods
private void MoveAI()
{
if (ballPos.y > transform.position.y)
{
rb.velocity = new Vector2(0, 1 * moveSpeed);
}
else if (ballPos.y == transform.position.y)
{
rb.velocity = new Vector2(0, 0);
Debug.Log("resting pos");
}
else
{
rb.velocity = new Vector2(0, -1 * moveSpeed);
}
}
private void UpdateBallPos()
{
ballPos = new Vector2(ballRef.transform.position.x, ballRef.transform.position.y);
}
#endregion
ballRef is linked to the ball that my game tracks during FixedUpdate
When the y coordinates for both start to become similar then my AI starts to bug out and start vibrating. It still tracks accurately but I'm not sure if there is a way to resolve my vibrating.
Comment