Advertisement
Guest User

Approach2

a guest
Jul 20th, 2023
15
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.29 KB | Gaming | 0 0
  1. using UnityEngine;
  2. using Unity.Collections;
  3. using Unity.Jobs;
  4. using UnityEngine.Jobs;
  5. using Unity.Mathematics;
  6.  
  7. public class BURST2 : MonoBehaviour {
  8.  
  9.     public struct MoveJob : IJobParallelForTransform {
  10.         [ReadOnly] public NativeArray<float3> positions;
  11.         public float deltaTime;
  12.         [SerializeField] public float3 playerPosition;  // cant provide playerpos, no matter how tried
  13.  
  14.         public void Execute(int index, TransformAccess transform) {
  15.             var pos = new float3(transform.position.x,transform.position.y,transform.position.z);
  16.             var direction = playerPosition - pos;
  17.             direction = math.normalize(direction);
  18.             pos += direction * positions[index] * deltaTime;
  19.             transform.position = pos;
  20.         }
  21.     }
  22.  
  23.     private TransformAccessArray m_AccessArray;
  24.     private NativeArray<float3> m_Positions;
  25.     private JobHandle m_MoveJobHandle;
  26.     private float3 m_PlayerPosition;
  27.  
  28.     private void Awake() {
  29.         m_AccessArray = new TransformAccessArray(0);
  30.         m_Positions = new NativeArray<float3>(0, Allocator.Persistent);
  31.     }
  32.  
  33.     private void OnDestroy() {
  34.         m_AccessArray.Dispose();
  35.         m_Positions.Dispose();
  36.     }
  37.  
  38.     public void RegisterEnemy(Transform enemyTransform) {
  39.         m_AccessArray.capacity += 1;
  40.         m_AccessArray.Add(enemyTransform);
  41.         var newPositions = new NativeArray<float3>(m_AccessArray.length, Allocator.Persistent);
  42.         NativeArray<float3>.Copy(m_Positions, newPositions, m_AccessArray.length - 1);
  43.         m_Positions.Dispose();
  44.         m_Positions = newPositions;
  45.     }
  46.  
  47.     public void SetPlayerPosition(float3 position) {
  48.         m_PlayerPosition = position;
  49.     }
  50.  
  51.     private void Update() {
  52.         if (m_AccessArray.length > 0) {
  53.             // init job
  54.             var moveJob = new MoveJob() {
  55.                 deltaTime = Time.deltaTime,
  56.                 positions = m_Positions,
  57.                 playerPosition = m_PlayerPosition
  58.             };
  59.             // run job
  60.             m_MoveJobHandle = moveJob.Schedule(m_AccessArray);
  61.             // wait for completion
  62.             m_MoveJobHandle.Complete();
  63.             // Debug.Log the position of the first enemy unit
  64.             Debug.Log(m_AccessArray[0].position);
  65.         }
  66.     }
  67. }
  68.  
Tags: Unity
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement