Search code examples
c#unity-game-enginepong

Mathf.Clamp Not working properly


I am developing a clone of pong game where my paddle move on X-Axis Code for it is below:

void Update () {

    Vector3 pos = transform.position;
    pos.x = Camera.main.ScreenToWorldPoint(Input.mousePosition).x;
    transform.position = new Vector3(Mathf.Clamp(pos.x,-14f,14f),-20f,0);
    transform.position = pos;

}

I think I am doing something stupid but I can't see it.


Solution

  • You are reassigning the position straight after clamping, ignoring that completely

    void Update () 
    {
        Vector3 pos = transform.position;
        pos.x = Mathf.Clamp(Camera.main.ScreenToWorldPoint(Input.mousePosition).x,
                                                            -14f, 14f);
        transform.position = pos;
    }
    

    Disclaimer: I haven't used unity so this makes some assumptions about the syntax being correct already.