Reputation: 677
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.
Upvotes: 0
Views: 433
Reputation: 348
Mathf.Clamp clamps a value between two numbers: https://docs.unity3d.com/ScriptReference/Mathf.Clamp.html
Mathf.Lerp interpolates between 2 values by a thrid one. https://docs.unity3d.com/ScriptReference/Mathf.Lerp.html
If I got the ideeas you want your AI to be locked in a specific area: minY, maxY, minX, maxX while it still follows the puck. So you should just clamp the position of the puck between those values.
void Update () {
transform.position = new Vector3(Mathf.Clamp(_puck.transform.position.x, minX, maxX), Mathf.Clamp(_puck.transform.position.y, minY, maxY),transform.position.z);}
Upvotes: 0