2
\$\begingroup\$

I was playing around with Unity's new Entity Component System and I was trying to implement a rotator system. This is what I came up with:

Component Data:

using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Jobs;
using Unity.Mathematics;
using Unity.Transforms;

[GenerateAuthoringComponent]
public struct RotatorComponent : IComponentData
{
    public float3 radiansPerSecond;
}

System:

using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Jobs;
using Unity.Mathematics;
using Unity.Transforms;

public class RotatorSystem : JobComponentSystem
{
    [BurstCompile]
    struct RotateJob : IJobForEach<Rotation, RotatorComponent>
    {
        public float DeltaTime;

        public void Execute(ref Rotation rotation, ref RotatorComponent rotator)
        {
            float3 rotationThisFrame = DeltaTime * rotator.radiansPerSecond;

            quaternion x = quaternion.AxisAngle(new float3(1.0f, 0.0f, 0.0f), rotationThisFrame.x);
            quaternion y = quaternion.AxisAngle(new float3(0.0f, 1.0f, 0.0f), rotationThisFrame.y);
            quaternion z = quaternion.AxisAngle(new float3(0.0f, 0.0f, 1.0f), rotationThisFrame.z);
            rotation.Value = math.mul(x, rotation.Value);
            rotation.Value = math.mul(y, rotation.Value);
            rotation.Value = math.mul(z, rotation.Value);
        }
    }

    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        return new RotateJob { DeltaTime = Time.DeltaTime }.Schedule(this, inputDeps);
    }
}

However, I think that the code shown in the system is not verry efficient. I am verry new to the new ECS stuff and I never did something with the new Unity.Mathematics. It would be nice if someone could show me whether the code shown in the system can be improved and if so how this would be possible.

\$\endgroup\$

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.