I’m currently learning ECS, and would like my objects to be able to rotate to face a point (IE: a turret turning to face the player). This is what I have currently:
A component that marks the entity as rotatable and stores related values:
using Unity.Entities;
using Unity.Mathematics;
[GenerateAuthoringComponent]
public struct Rotateable : IComponentData
{
public RotationType rotationType;
public float rotationSpeed;
public bool hasTarget;
public quaternion rotationTarget;
}
A system which either automatically snaps the entity to the new rotation or rotates slowly (enum is smooth or snap)
Entities.ForEach((ref Rotation rot, in Rotateable rotateable) =>
{
var target = rotateable.rotationTarget;
var speed = rotateable.rotationSpeed;
var type = rotateable.rotationType;
if (rot.Value.Equals(target)) return;
if (type == RotationType.snapToPoint)
{
//snap to rotation
rot.Value = target;
}
else
{
if (!rot.Value.Equals(target))
{
//rotate at rotationSpeed to match needed angle
var delta = quaternion.RotateX(math.radians(speed * dt));
var step = math.mul(target, delta);
rot.Value = math.mul(step, rot.Value);// FIRST ATTEMPT (get errors)
}
}
}).Schedule();
And lastly is a temporary targeting system that generates a random target for rotatable (which I just realized is spelled wrong
rng.NextInt();
var rngTemp = rng;
Entities.ForEach((ref Rotateable rot, in Translation trans) =>
{
var newTarget = new float3();
newTarget.x = rngTemp.NextInt(5);
newTarget.y = rngTemp.NextInt(5);
newTarget.z = rngTemp.NextInt(5);
if (!rot.hasTarget)
{
rot.rotationTarget = quaternion.LookRotation(newTarget - trans.Value, new float3(0, 1, 0));
rot.hasTarget = true;
}
}
).Schedule();
this.CompleteDependency();
I’ve mostly been experimenting to see what works, as I’m still new to ECS. I’d troubleshoot it myself, but I’m getting fun and descriptive errors like
“Invalid AABB a”
“Invalid AABB aabb”
“Assertion failed on expression: ‘IsFinite(d)’”
I’m not afraid to admit I’m completely lost on this. My current best guess is it has something to do with either
A, the targeting system improperly making quaternions
B, the physics bodies spazzing out when I try to set Rotation.Value
C, my smooth rotation equation being wrong
Any help would be greatly appreciated!
EDIT: I’ve gone through some troubleshooting, and it appears the errors are from PhysicsBody spazzing out from changing Rotation.Value. I’m working on rotating my entities with the built in PhysicsVelocity Component