「Unity/3d/キャラクタ移動/前後回転」の版間の差分
提供: 初心者エンジニアの簡易メモ
(→前後移動で左右で回転するサンプル) |
|||
(同じ利用者による、間の3版が非表示) | |||
行1: | 行1: | ||
− | == | + | ==前後移動で左右で回転するサンプル== |
− | + | ||
<pre> | <pre> | ||
using System.Collections; | using System.Collections; | ||
行10: | 行9: | ||
float x, z; | float x, z; | ||
float speed = 0.1f; | float speed = 0.1f; | ||
− | float | + | float rotateSpeed = 1f; |
GameObject cam; | GameObject cam; | ||
Quaternion cameraRot, characterRot; | Quaternion cameraRot, characterRot; | ||
− | |||
− | |||
float minX = -90f, maxX = 90f; | float minX = -90f, maxX = 90f; | ||
void Start() | void Start() | ||
行24: | 行21: | ||
void Update() | void Update() | ||
{ | { | ||
− | float xRot = Input.GetAxisRaw("Horizontal") * | + | float xRot = Input.GetAxisRaw("Horizontal") * rotateSpeed; |
characterRot *= Quaternion.Euler(0, xRot, 0); | characterRot *= Quaternion.Euler(0, xRot, 0); | ||
cameraRot = ClampRotation(cameraRot); | cameraRot = ClampRotation(cameraRot); | ||
行35: | 行32: | ||
transform.position += cam.transform.forward * z + cam.transform.right * x; | transform.position += cam.transform.forward * z + cam.transform.right * x; | ||
} | } | ||
− | public Quaternion ClampRotation(Quaternion | + | public Quaternion ClampRotation(Quaternion qua) |
{ | { | ||
− | + | qua.x /= qua.w; | |
− | + | qua.y /= qua.w; | |
− | + | qua.z /= qua.w; | |
− | + | qua.w = 1f; | |
− | float angleX = Mathf.Atan( | + | float angleX = Mathf.Atan(qua.x) * Mathf.Rad2Deg * 2f; |
angleX = Mathf.Clamp(angleX, minX, maxX); | angleX = Mathf.Clamp(angleX, minX, maxX); | ||
− | + | qua.x = Mathf.Tan(angleX * Mathf.Deg2Rad * 0.5f); | |
− | return | + | return qua; |
} | } | ||
} | } | ||
</pre> | </pre> | ||
参考:https://www.popii33.com/unity-first-person-camera/ | 参考:https://www.popii33.com/unity-first-person-camera/ |
2022年12月12日 (月) 11:03時点における最新版
前後移動で左右で回転するサンプル
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CharacterControl : MonoBehaviour { float x, z; float speed = 0.1f; float rotateSpeed = 1f; GameObject cam; Quaternion cameraRot, characterRot; float minX = -90f, maxX = 90f; void Start() { cam = GameObject.Find("Main Camera"); cameraRot = cam.transform.localRotation; characterRot = transform.localRotation; } void Update() { float xRot = Input.GetAxisRaw("Horizontal") * rotateSpeed; characterRot *= Quaternion.Euler(0, xRot, 0); cameraRot = ClampRotation(cameraRot); transform.localRotation = characterRot; } private void FixedUpdate() { x = 0; z = Input.GetAxisRaw("Vertical") * speed; transform.position += cam.transform.forward * z + cam.transform.right * x; } public Quaternion ClampRotation(Quaternion qua) { qua.x /= qua.w; qua.y /= qua.w; qua.z /= qua.w; qua.w = 1f; float angleX = Mathf.Atan(qua.x) * Mathf.Rad2Deg * 2f; angleX = Mathf.Clamp(angleX, minX, maxX); qua.x = Mathf.Tan(angleX * Mathf.Deg2Rad * 0.5f); return qua; } }