I’ve been trying to dig around for a proper way to make my object face the direction it’s going in a top-down space shooter. I’m an absolute beginner and have yet to find my way around the nuances of the API.
Best I could find relevant to what I’m asking is this thread: Calculating angles using Atan2 - but it discusses more on the math around it rather than API.
I have the following snippet on the OnUpdate
of my Ship Control ISystem
:
foreach (var (transform, input, momentum) in SystemAPI
.Query<RefRW<LocalTransform>, RefRO<PlayerMoveInput>, RefRW<PlayerMomentum>>()
.WithAll<Ship>())
{
if (!input.ValueRO.Value.Equals(float2.zero))
{
momentum.ValueRW.Value += input.ValueRO.Value * SystemAPI.Time.DeltaTime;
var momentumDirection = momentum.ValueRW.Value / math.length(momentum.ValueRW.Value);
//Is there a better way to do this?
transform.ValueRW.Rotation = quaternion.AxisAngle(math.forward(), math.atan2(-momentumDirection.x, momentumDirection.y));
}
else
{
momentum.ValueRW.Value = math.lerp(momentum.ValueRW.Value, float2.zero, 0.5f * SystemAPI.Time.DeltaTime);
}
transform.ValueRW.Position.xy += momentum.ValueRW.Value * SystemAPI.Time.DeltaTime;
}
What I’m not sure about here is whether there’s a more elegant way to rotate the object properly aside from transposing the parameters of atan2()
. If I do it normally like math.atan2(momentumDirection.y, momentumDirection.x)
the ship goes into the direction using its “right” side rather than pointing with its nose (“up” side). I know this is because of how the axes are oriented with respect to the object but I just feel like there would have been a more intuitive way to do it.