0

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.

JonHerbert
  • 647
  • 1
  • 8
  • 23

2 Answers2

1

Your minY is greater than maxY.

I think you should invert them.

dogiordano
  • 691
  • 6
  • 13
0

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);}
pasotee
  • 338
  • 2
  • 12
  • The way my game works would, unfortunately, make this more of a hack than a solution. – JonHerbert Mar 18 '17 at 13:36
  • What makes you desired behaviour different ? Do you want it to move slower to where the puck is? – pasotee Mar 18 '17 at 14:29
  • I don't need to clamp the puck as it interacts perfectly with the tables colliders, however the computers paddle needs to only interact with half the table therefore I need to make sure it's y value, in this case, is clamped. If I don't also clamp the x, I get an overlap with the borders which is ugly. If I don't clamp anything the computer will just follow the puck around the entirety of the table which I don't want. But anyway, the issue was with my min and max y values being backwards. Silly mistake. – JonHerbert Mar 20 '17 at 17:09