我开始使用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);
});
答案 0 :(得分:1)
要从四元数中获取向量,只需将其与正向向量相乘即可,例如:
if (Input.GetKey(KeyCode.W))
{
Vector forward = tmpRotation * float3(0,0,1);
tmpTranslation += forward * Time.deltaTime * PlayerSpeed;
}
对于旋转部分,正如您所说的// this always set the same angle
。看起来您正在创建一个新的静态角度。尝试更改以当前角度相乘,就像四元数相乘以合并一样。示例:
if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
{
tmpRotation = mul(tmpRotation, quaternion.RotateZ(PlayerRotationFactor));
}
旁注:我还是Unity ECS的新手,我还没有测试以上代码。
答案 1 :(得分:0)
// correct forward
if (Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.UpArrow))
{
float3 forwardVector = math.mul(rotation.Value, new float3(0, 1, 0));
newTranslation += forwardVector * Time.deltaTime * PlayerSpeed;
}
// correct rotation
if (Input.GetKey(KeyCode.A) || Input.GetKey(KeyCode.LeftArrow))
{
quaternion newRotation = math.mul(rotation.Value, quaternion.RotateZ(PlayerRotationFactor * Time.deltaTime));
// insert new value to the component
PostUpdateCommands.SetComponent(entity, new Rotation { Value = newRotation });
}
// thx akaJag