oniyarai’s tech memo

oniyarai’s tech memo

すぐ忘れる自分に捧げるメモ

取りうる値の制限(オブジェクトの移動範囲の制限など)

Mathf.Clamp intまたはfloatの値の範囲を制限する

使用法はIntもFloatも同様。第一引数で与えられるValueを第二引数(最小値)、第三引数(最大値)の間に制限する。 この場合表示される値は3となる(最大値より大きい10であるため)。

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour
{
    // Use this for initialization
    void Start()
    {
        // Clamps the value 10 to be between 1 and 3.
        // prints 3 to the console

        Debug.Log(Mathf.Clamp(10, 1, 3));
    }
}

これを利用してオブジェクトの移動などに制限を加える。 Mathf.Clampでオブジェクトが取りうるtransform.positionの値を-8~8に制限し、その範囲を超えてオブジェクトが移動することを防ぐ。

    void Update()
    {
        // X方向に入力*速度*時間分移動させる
        this.transform.Translate(Input.GetAxisRaw("Horizontal") * MoveSpeed * Time.deltaTime, 0, 0);
        // X方向の移動範囲を制限する
        this.transform.position = new Vector2(Mathf.Clamp(this.transform.position.x, -8.0f, 8.0f), transform.position.y);
    }