Course contentsShow
← Unity Game Development
Lesson 681 of 82810. VFX and Post-ProcessingFree lesson

Implementing Particle Attraction and Repulsion

Develop logic to make particles interact with specific game objects or player positions using custom distance-based mathematical calculations.

In this lesson, you will learn how to build a dynamic attraction and repulsion system within the VFX Graph by calculating custom force vectors based on the distance between particles and a target object.

The Physics of Influence

To make particles react to a player or a specific GameObject, we don’t rely on built-in collision physics; instead, we manipulate the particle's velocity attribute directly via the GPU. The core logic relies on the Vector3.Direction calculation: if you subtract the particle’s current position from the target position, you get a vector pointing toward the target.

By normalizing this vector and multiplying it by a "strength" value divided by the squared distance, we simulate a realistic gravitational pull.

Implementing the Logic

Inside your VFX Graph, you can implement this by adding a Custom HLSL node within your Update block. Here is the mathematical approach:

// Assuming 'TargetPosition' is a Vector3 property
// 'ParticlePosition' is the current particle's position
float3 direction = TargetPosition - ParticlePosition;
float distance = length(direction);
float3 force = normalize(direction) * (Strength / (distance * distance + 0.1));

// Apply this as an acceleration to the particle
OutputVelocity = InputVelocity + (force * deltaTime);

Controlling Behavior

The 0.1 constant in the denominator prevents a "division by zero" error when a particle gets too close to the target, which would otherwise send it flying at infinite speed. To toggle between attraction and repulsion, simply multiply your Strength property by -1.

Because this happens inside the VFX Update loop, every particle is recalculated every frame. You can map the Strength property to a VFX Property Binder on your C# script. This allows your gameplay code to push or pull particles based on player input—for example, holding a "gravity gun" button can swap your strength variable from a positive value (attraction) to a negative one (repulsion) in real-time.

Key Takeaway: By calculating the normalized vector between a target and a particle and modulating it by the inverse square of the distance, you can create high-performance, GPU-accelerated attraction and repulsion forces that feel physically grounded.