0

ゲーム オブジェクトの y の値を 4 と -4 にクランプしようとしていますが、ymax と ymin にジャンプし続けます。私が考えることができる唯一の理由は、最後の行コードのためです。ゲームでは x 値と z 値が変更されないため、y 値のみをクランプしています。ゲームはポンに似ています。

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

}
4

2 に答える 2

0

、 の値を初期化しませんでしyMinyMax

また、 をelse if2 番目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;
    }
}
于 2015-09-02T20:34:41.410 に答える