gpt4 book ai didi

c# - 如何在 Unity (ECS) 中旋转四元数并计算方向向量

转载 作者:行者123 更新时间:2023-12-04 01:42:57 112 4
gpt4 key购买 nike

我开始使用 ECS,我有一个旋转组件(四元数)和一个平移组件(float3)。我正在编写一个系统来处理用户输入并旋转和/或向前移动播放器。

问题是我不知道该怎么做。我认为现有的 API 是缺乏的。

// Before it was easy
if (Input.GetKey(KeyCode.W))
var newPostion = new Vector3(player.Position.x, player.Position.y, 0.3f)
+ _playerTransform.up * Time.deltaTime * PlayerSpeed;

if (Input.GetKey(KeyCode.A))
_playerTransform.Rotate(new Vector3(0, 0, PlayerRotationFactor));

// now it is not - that's part of the system's code
Entities.With(query).ForEach((Entity entity, ref Translation translation, ref Rotation rotation) =>
{
float3 tmpTranslation = translation.Value;
quaternion tmpRotation = rotation.Value;

if (Input.GetKey(KeyCode.W))
// how to retrieve forward vector from the quaternion
tmpTranslation.y += Time.deltaTime * PlayerSpeed;

if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
// this always set the same angle
tmpRotation = quaternion.RotateZ(PlayerRotationFactor);

// ECS need this
var newTranslation = new Translation { Value = tmpTranslation };
PostUpdateCommands.SetComponent(entity, newTranslation);
var newRotation = new Rotation { Value = tmpRotation };
PostUpdateCommands.SetComponent(entity, newRotation);
});

最佳答案

要从四元数中获取向量,您可以简单地将它与前向向量相乘,例如:

if (Input.GetKey(KeyCode.W))
{
Vector forward = tmpRotation * float3(0,0,1);
tmpTranslation += forward * Time.deltaTime * PlayerSpeed;
}

对于旋转部分,如您所说,//始终设置相同的角度。看起来你正在创造一个新的静态角度。尝试改变以与当前角度相乘,就像四元数相乘以组合一样。示例:

if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
{
tmpRotation = mul(tmpRotation, quaternion.RotateZ(PlayerRotationFactor));
}

旁注:我对 Unity ECS 也有点陌生,我没有测试过上面的代码。

关于c# - 如何在 Unity (ECS) 中旋转四元数并计算方向向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56619907/

112 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com