Something went wrong. Try again.
A unity based gravity simulation thing inspired by interplanetary (the game)
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162using Physics.Components;using Unity.Burst;using Unity.Collections;using Unity.Entities;using Unity.Mathematics;using Unity.Transforms;
namespace Physics.Systems{ public struct GravitySystemConfig : IComponentData { public float G; } [UpdateInGroup(typeof(FixedStepSimulationSystemGroup))] partial struct GravitySystem : ISystem { [BurstCompile] public void OnCreate(ref SystemState state) { state.EntityManager.AddComponentData(state.SystemHandle, new GravitySystemConfig { G = 1 }); }
[BurstCompile] public void OnUpdate(ref SystemState state) { var config = state.EntityManager.GetComponentData<GravitySystemConfig>(state.SystemHandle); var entities = new NativeList<(Entity, float3, float)>(Allocator.Temp); foreach (var (particle, transform, entity) in SystemAPI.Query<RefRO<Particle>, RefRO<LocalTransform>>().WithEntityAccess() ) { entities.Add((entity, transform.ValueRO.Position, particle.ValueRO.Mass)); } foreach (var (particle, transform, entity) in SystemAPI.Query<RefRW<Particle>, RefRW<LocalTransform>>().WithNone<Fixed>().WithEntityAccess() ) { float3 acc = 0; var position = transform.ValueRO.Position; foreach (var (src, srcPosition, mass) in entities) { if (entity == src) continue; acc += config.G * mass / math.distancesq(srcPosition, position) * math.normalize(srcPosition - position); }
particle.ValueRW.Acceleration = acc; } }
[BurstCompile] public void OnDestroy(ref SystemState state) { } }}