回答編集履歴
1
急激な振り向きを避けるための改善案を追記
test
CHANGED
@@ -65,3 +65,101 @@
|
|
65
65
|
}
|
66
66
|
|
67
67
|
```
|
68
|
+
|
69
|
+
|
70
|
+
|
71
|
+
※おまけ
|
72
|
+
|
73
|
+
ターゲットがキャラクターの背後を横切るときなどには、首が一瞬で逆向きに回るのが気に入らないかもしれません。
|
74
|
+
|
75
|
+
一案としては、[Quaternion.Slerp](https://docs.unity3d.com/ja/current/ScriptReference/Quaternion.Slerp.html)で回転を混ぜ合わせて動きを緩和する手があるかと思います。
|
76
|
+
|
77
|
+
```C#
|
78
|
+
|
79
|
+
using System.Collections;
|
80
|
+
|
81
|
+
using System.Collections.Generic;
|
82
|
+
|
83
|
+
using UnityEngine;
|
84
|
+
|
85
|
+
|
86
|
+
|
87
|
+
public class LookAtMe : MonoBehaviour
|
88
|
+
|
89
|
+
{
|
90
|
+
|
91
|
+
public Transform neckBone;
|
92
|
+
|
93
|
+
public GameObject watchTarget;
|
94
|
+
|
95
|
+
public float _plusRotationY;//Inspector上で-90
|
96
|
+
|
97
|
+
public float _plusRotationZ;//Inspector上で-90
|
98
|
+
|
99
|
+
public float _maxAngle = 60;
|
100
|
+
|
101
|
+
public float _smoothingFactor = 6;
|
102
|
+
|
103
|
+
|
104
|
+
|
105
|
+
private Quaternion previousRotation;
|
106
|
+
|
107
|
+
|
108
|
+
|
109
|
+
protected virtual void LateUpdate()
|
110
|
+
|
111
|
+
{
|
112
|
+
|
113
|
+
if (neckBone != null)
|
114
|
+
|
115
|
+
{
|
116
|
+
|
117
|
+
if (watchTarget != null)
|
118
|
+
|
119
|
+
{
|
120
|
+
|
121
|
+
// 制限なしの回転を求め...
|
122
|
+
|
123
|
+
var rotation = Quaternion.LookRotation(watchTarget.transform.position - neckBone.position);
|
124
|
+
|
125
|
+
|
126
|
+
|
127
|
+
// その回転角を_maxAngleまでに制限し...
|
128
|
+
|
129
|
+
rotation = Quaternion.RotateTowards(Quaternion.identity, rotation, _maxAngle);
|
130
|
+
|
131
|
+
|
132
|
+
|
133
|
+
// 軸合わせを行い...
|
134
|
+
|
135
|
+
rotation *= Quaternion.Euler(0, _plusRotationY, _plusRotationZ);
|
136
|
+
|
137
|
+
|
138
|
+
|
139
|
+
// Slerpで前回の回転とブレンドし、previousRotationにセットし...
|
140
|
+
|
141
|
+
previousRotation = Quaternion.Slerp(previousRotation, rotation, Time.deltaTime * _smoothingFactor);
|
142
|
+
|
143
|
+
|
144
|
+
|
145
|
+
// その回転を首のrotationとする
|
146
|
+
|
147
|
+
neckBone.transform.rotation = previousRotation;
|
148
|
+
|
149
|
+
|
150
|
+
|
151
|
+
// 首の回転がアニメーションにより制御されている場合、それによって回転が毎回更新されてしまうはずなので
|
152
|
+
|
153
|
+
// 下記のようにやったのでは、なめらかに回ってくれないかもしれません
|
154
|
+
|
155
|
+
// neckBone.transform.rotation = Quaternion.Lerp(neckBone.transform.rotation, rotation, Time.deltaTime);
|
156
|
+
|
157
|
+
}
|
158
|
+
|
159
|
+
}
|
160
|
+
|
161
|
+
}
|
162
|
+
|
163
|
+
}
|
164
|
+
|
165
|
+
```
|