Search code examples
c#unity-game-enginetransformclampjitter

Gameobject does not clamp but rather jitters


I am trying to clamp the value of y for my game object to be 4 and -4 but it keeps jumping to the ymax and ymin. and the only reason i can think of is because of the last line code. i am only clamping the y values because the x and z values are not changed in the game. the game is similar to pong.

using UnityEngine;
using System.Collections;

public class Movement1 : MonoBehaviour 
{

public Vector3 Pos;
void Start () 
{
    Pos = gameObject.transform.localPosition;
}

public float yMin, yMax;
void Update () 
{
    if (Input.GetKey (KeyCode.W)) {
        transform.Translate (Vector3.up * Time.deltaTime * 10);
    }
    if (Input.GetKey (KeyCode.S)) {
        transform.Translate (Vector3.down * Time.deltaTime * 10);
    }

    Pos.y = Mathf.Clamp(Pos.y,yMin,yMax);
    gameObject.transform.localPosition = Pos;
}

}

Solution

  • The Pos.y assignment never happens, because you can't change just the y-value; you have to make a new Vector3. Try the following:

    using UnityEngine;
    using System.Collections;
    
    public class Movement1 : MonoBehaviour 
    {
    
    public float yMin, yMax; // be sure to set these in the inspector
    void Update () 
    {
    
        if (Input.GetKey (KeyCode.W)) {
            transform.Translate (Vector3.up * Time.deltaTime * 10);
        }
        if (Input.GetKey (KeyCode.S)) {
            transform.Translate (Vector3.down * Time.deltaTime * 10);
    
        }
    
        float clampedY = Mathf.Clamp(transform.localPosition.y,yMin,yMax);
        transform.localPosition = new Vector3 (transform.localPosition.x, clampedY, transform.localPosition.z);
    
    }
    
    }