Gameobject没有钳制,而是紧张不安

时间:2015-09-02 20:23:58

标签: c# unity3d transform clamp jitter

我试图将我的游戏对象的y值限制为4和-4,但它会一直跳到ymax和ymin。我能想到的唯一原因是因为最后一行代码。我只是钳制y值,因为游戏中的x和z值没有改变。游戏类似于乒乓球。

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

}

2 个答案:

答案 0 :(得分:0)

您没有初始化yMinyMax的所有值。

此外,您应该为第二个else if添加Translate,否则按两者都会导致抖动。

但实际上,它应该更像是这样:

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

答案 1 :(得分:0)

Pos.y任务永远不会发生,因为你不能只改变y值;你必须制作一个新的Vector3。请尝试以下方法:

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

}

}