Skip to content

Instantly share code, notes, and snippets.

@Cj-bc
Last active November 19, 2019 01:25
Show Gist options
  • Save Cj-bc/1ddfe4a57b18a7f9339aa3d0cff155b7 to your computer and use it in GitHub Desktop.
Save Cj-bc/1ddfe4a57b18a7f9339aa3d0cff155b7 to your computer and use it in GitHub Desktop.
Unityで、カメラの可動域をMathf.Clampで制限しようと思った時におこった挙動の理由と解決方法 https://twitter.com/Cj_bc_sd/status/1196352398253387777?s=20
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ClampTest : MonoBehaviour
{
public float _x;
public float axis;
// Update is called once per frame
void Update()
{
_x = transform.localEulerAngles.x;
Debug.Log($"localEulerAngles.x: {_x}");
axis = Input.GetAxis("Mouse Y");
transform.localEulerAngles = new Vector3(Mathf.Clamp(_x - 10, -40.0f, 40.0f), 0, 0);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ClampTest : MonoBehaviour
{
public float _x;
public float axis;
// Update is called once per frame
void Update()
{
_x = transform.localEulerAngles.x;
Debug.Log($"localEulerAngles.x: {_x}");
axis = Input.GetAxis("Mouse Y");
if (180 <= _x) _x = -(360 - _x);
transform.localEulerAngles = new Vector3(Mathf.Clamp(_x - 10, -40.0f, 40.0f), 0, 0);
}
}

問題の挙動

  • Mathf.Clamp(v, min, max)(min < 0 < max)とした時、0 < vとなった時にmaxの値をとる

問題の原因

  • transform.localEulerAnglesの値域は0~360だった
  • インスペクター上では負数もそのまま表示されるが、実際は内部で0~360°の値に変換されている模様

そうなると、以下のように理解ができる:

float x = transform.localEulerAngle.x;
Mathf.Clamp(x, -40, 40) // 元の式
transform.localEulerAngle = new Vector3(-100, 0, 0);
// この直後、Unity側で次の処理が入る模様
transform.localEulerAngle = new Vector3(360 + -100, 0, 0);
// よって、Mathf.Clampは
Mathf.Clamp(x, -40, 40);
Mathf.Clamp(260, -40, 40);
40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment