0

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;
}

}
31eee384
  • 2,748
  • 2
  • 18
  • 27
Iven P.
  • 25
  • 2

2 Answers2

0

You didn't initialize any values for the yMin, yMax.

Also, you should put an else if for the second Translate, otherwise pressing both could cause jitters.

But really, it should be more like this:

using UnityEngine;
using System.Collections;

public class Movement1 : MonoBehaviour 
{
    public Vector3 Pos;
    public float speed = 10f;
    public float yMin = 10f;
    public float yMax = 50f;

    void Update () 
    {
        Pos = gameObject.transform.localPosition;

        if (Input.GetKey (KeyCode.W))
            Pos += (Vector3.up * Time.deltaTime * speed);

        if (Input.GetKey (KeyCode.S))
            Pos += (Vector3.down * Time.deltaTime * speed);

        Pos.y = Mathf.Clamp(Pos.y,yMin,yMax);
        gameObject.transform.localPosition = Pos;
    }
}
maraaaaaaaa
  • 7,749
  • 2
  • 22
  • 37
0

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);

}

}
user3071284
  • 6,955
  • 6
  • 43
  • 57