Facebook
From Violet Horse, 3 Years ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 153
  1. public class TurretAim : ComponentSystem
  2. {
  3.     protected override void OnUpdate()
  4.     {
  5.         EntityManager entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;
  6.         Entities.WithAll<HasTarget>().ForEach((Entity entity, ref Translation turretPos, ref Rotation turretRot, ref Angle angle, ref HasTarget target)=>{
  7.                 if(target.target != Entity.Null && EntityManager.Exists(target.target)){
  8.                     Translation enemyPos = entityManager.GetComponentData<Translation>(target.target);
  9.  
  10.                     float3 targetVec = enemyPos.Value - turretPos.Value;
  11.  
  12.                     float len = targetVec.x*targetVec.x + targetVec.y*targetVec.y + targetVec.z*targetVec.z;
  13.                     len = Mathf.Sqrt(len);
  14.  
  15.                     float a = targetVec.z / len;
  16.  
  17.                     a = Mathf.Acos(a);
  18.  
  19.                     float rad = angle.angle * Mathf.Deg2Rad;
  20.  
  21.                     if(targetVec.x <  0) a = -a;
  22.  
  23.                     float speedInDeg = 90.0f;
  24.                     float maxDelta = Mathf.Deg2Rad * speedInDeg * Time.DeltaTime;
  25.  
  26.                     float newRot = Mathf.MoveTowards(rad, a, maxDelta);
  27.                     angle.angle = newRot * Mathf.Rad2Deg;
  28.                     turretRot.Value = quaternion.EulerXYZ(0, newRot, 0);
  29.                 }
  30.                 else{
  31.                     PostUpdateCommands.RemoveComponent(entity, typeof(HasTarget));
  32.                 }
  33.            
  34.  
  35.         });
  36.     }
  37. }