Search code examples
unity-game-engineclamplerp

Clamp gameobject to within borders while slowly following another along x and y


I am trying to make an air hockey game and I need to clamp the AI into a specific area whilst it follows the puck around the board when it's in its half. I thought the following code would work but I'm getting some weird behaviour from the paddle where it will either a) get stuck at y=minY on start of the level or b) it will seemingly phase between minY and maxY continuously.

public float speed = 0.075f;
public float minX = -3.7f, minY = 6.7f, maxX = 3.7f, maxY = 0.5f;

void Update () {
    transform.position = new Vector3(Mathf.Clamp(Mathf.Lerp(transform.position.x, _puck.transform.position.x, speed), minX, maxX), 
                                     Mathf.Clamp(Mathf.Lerp(transform.position.y, _puck.transform.position.y, speed), minY, maxY),
                                     transform.position.z);
}

Thanks for any help.

EDIT I should add that if I only use the clamp on the y it works as expected, however it may clip out of the x over time if I don't clamp that too.


Solution

  • Your minY is greater than maxY.

    I think you should invert them.