将对象旋转到目标,同时旋转以匹配地形坡度
Rotate object to target, while being rotated to match the terrain slope
在上图中
- 红色向量是蜘蛛的前向向量
- 蓝色矢量是表示蜘蛛与其目标之间方向的矢量
在下面的代码中,orientation
是代表地形法线的向量,因此蜘蛛会与其对齐:
Vector3 orientation = GetTerrainNormal();
Quaternion rotationNeeded = Quaternion.FromToRotation(Vector3.up, orientation);
transform.rotation = Quaternion.RotateTowards(
transform.rotation,
rotationNeeded,
RotationSpeed * Time.deltaTime
);
我的问题是我无法让蜘蛛面向它的目标...当我添加任何代码使其朝向它旋转时,它不再与地形的法线对齐,它说直.. .
所以基本上,我怎样才能让蜘蛛在 Y 世界轴上旋转(我认为),同时仍然旋转以匹配坡度?
完整答案
如果它对其他人有帮助,这里是完整答案:
Vector3 orientation = GetTerrainNormal();
Vector3 directionToTarget = (target.position - transform.position).Y(0);
float d = Vector3.Dot(directionToTarget, orientation);
directionToTarget -= d * orientation;
if (directionToTarget.sqrMagnitude > 0.00001f) {
directionToTarget.Normalize();
Quaternion rotationNeeded = Quaternion.LookRotation(directionToTarget, orientation);
transform.rotation = Quaternion.RotateTowards(
transform.rotation,
rotationNeeded,
xRotationSpeed * Time.deltaTime
);
}
Unity 论坛上的这个回答非常有帮助:https://forum.unity.com/threads/look-at-object-while-aligned-to-surface.515743/
试试这个
Vector3 directionToTarget = target.transform.position - transform.position;
Quaternion rotationNeeded = Quaternion.LookRotation(directionToTarget, orientation);
首先,我不确定您为什么需要代码来手动将蜘蛛定向到地形。您可以将蜘蛛设为 Rigidbody
,Unity 引擎会为您处理。
无论如何,您想要围绕 local Y 轴旋转蜘蛛(这将保持当前方向)。
您可以使用 transform.LookAt()
(指图片中的蓝色向量)(documented here) 并将向上向量作为第二个参数传递。
在上图中
- 红色向量是蜘蛛的前向向量
- 蓝色矢量是表示蜘蛛与其目标之间方向的矢量
在下面的代码中,orientation
是代表地形法线的向量,因此蜘蛛会与其对齐:
Vector3 orientation = GetTerrainNormal();
Quaternion rotationNeeded = Quaternion.FromToRotation(Vector3.up, orientation);
transform.rotation = Quaternion.RotateTowards(
transform.rotation,
rotationNeeded,
RotationSpeed * Time.deltaTime
);
我的问题是我无法让蜘蛛面向它的目标...当我添加任何代码使其朝向它旋转时,它不再与地形的法线对齐,它说直.. .
所以基本上,我怎样才能让蜘蛛在 Y 世界轴上旋转(我认为),同时仍然旋转以匹配坡度?
完整答案
如果它对其他人有帮助,这里是完整答案:
Vector3 orientation = GetTerrainNormal();
Vector3 directionToTarget = (target.position - transform.position).Y(0);
float d = Vector3.Dot(directionToTarget, orientation);
directionToTarget -= d * orientation;
if (directionToTarget.sqrMagnitude > 0.00001f) {
directionToTarget.Normalize();
Quaternion rotationNeeded = Quaternion.LookRotation(directionToTarget, orientation);
transform.rotation = Quaternion.RotateTowards(
transform.rotation,
rotationNeeded,
xRotationSpeed * Time.deltaTime
);
}
Unity 论坛上的这个回答非常有帮助:https://forum.unity.com/threads/look-at-object-while-aligned-to-surface.515743/
试试这个
Vector3 directionToTarget = target.transform.position - transform.position;
Quaternion rotationNeeded = Quaternion.LookRotation(directionToTarget, orientation);
首先,我不确定您为什么需要代码来手动将蜘蛛定向到地形。您可以将蜘蛛设为 Rigidbody
,Unity 引擎会为您处理。
无论如何,您想要围绕 local Y 轴旋转蜘蛛(这将保持当前方向)。
您可以使用 transform.LookAt()
(指图片中的蓝色向量)(documented here) 并将向上向量作为第二个参数传递。