実現したいこと
初めてこちらで質問いたします。
キーボード入力でキャラクターを移動させ、キャラクターは移動方向を向かせたいです。
発生している問題・分からないこと
壁に接触する前は問題なくキャラが移動方向を向きます。
壁に接触しながら壁に向かって斜めに移動を行うと、移動方向に向きが変わりきらず、移動方向の回転とキャラの回転に誤差が発生します。
誤差発生中にキーボード入力をやめて移動しなくすると、キャラが移動方向を向ききり、この誤差は無くなります。
誤差がある状態で状態で壁から離れると誤差が残り、再度壁に接触して誤差が無くさないと移動方向を向けなくなります。
Quaternion.Slerpの結果をtronsform.localRotationに格納しているのですが、
誤差が発生している時のみtronsform.localRotationとmoveRotationが一致していませんでした。
該当のソースコード
using System.Collections; using System.Collections.Generic; using UnityEngine; public class question : MonoBehaviour { Rigidbody rb; CapsuleCollider col; private float maxspeed = 5.0f; private Vector3 moveDirection = Vector3.zero; private Quaternion moveRotation = Quaternion.identity; // Start is called before the first frame update void Start() { rb = GetComponent<Rigidbody>(); rb.constraints = RigidbodyConstraints.FreezeRotationX | RigidbodyConstraints.FreezeRotationZ; col = GetComponent<CapsuleCollider>(); } // Update is called once per frame void FixedUpdate() { Vector3 inputDirection = new Vector3(Input.GetAxis("Horizontal"), 0.0f, Input.GetAxis("Vertical")); if (inputDirection != Vector3.zero) moveDirection = inputDirection; float _maxspeed = maxspeed; //移動ベクトルが1より大きい場合は1に正規化(斜め移動の高速化を防止) if (moveDirection.magnitude > 1) { moveDirection.Normalize(); } //力を求める(F = dv * mass / dt) float moveForce = (_maxspeed * moveDirection.magnitude) * rb.mass / Time.fixedDeltaTime; //移動力を加える rb.AddForce(moveDirection * moveForce, ForceMode.Force); //ドリフト対策 Vector3 driftCounter = new Vector3(rb.velocity.x, 0, rb.velocity.z); rb.AddForce(-driftCounter / Time.fixedDeltaTime, ForceMode.Force); //横移動が最高速を超えた場合最高速に抑える Vector3 _velocity = new Vector3(rb.velocity.x, 0, rb.velocity.z); if (_velocity.magnitude > _maxspeed) { _velocity.Normalize(); rb.velocity = new Vector3(_velocity.x * _maxspeed, rb.velocity.y, _velocity.z * _maxspeed); } //移動ベクトルが閾値より大きい場合のみキャラクターの向きを更新する if (moveDirection.magnitude > 0.3f) { moveRotation = Quaternion.LookRotation(moveDirection); } transform.localRotation = Quaternion.Slerp(transform.localRotation, moveRotation, 10.0f * Time.fixedDeltaTime); } }
試したこと・調べたこと
- teratailやGoogle等で検索した
- ソースコードを自分なりに変更した
- 知人に聞いた
- その他
上記の詳細・結果
Googleなどでキャラクターを回転させる方法などを調べましたが、
壁に接触した状態でのキャラクターの回転についての情報を見つけられませんでした。
補足
2021.3.15f1

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。