The problem is this:
I have a scene of a bunch of spheres bouncing around like particles in a contained area.
Via TUIO, I have a point that appears on the scene and repels particles, but only if they come within a close radius.
This all works fine, except that when I put a TUIO point on the scene, the particles that get repelled by the TUIO point never stop being affected by the repulsion, no matter how far away they disperse, until the TUIO point disappears from the scene completely.
I have the repulsion script being called AFTER a check to see whether the particle is in range of the TUIO repulsor. If there is no TUIO repulsor in range, it returns null and so should not be repelling anything. Yet I find when looking in scene view, all the particles end up bouncing repeatedly against the walls, stuck there until the TUIO repulsor disappears.
I’d appreciate any help. Here’s the code.
Thanks!
using UnityEngine;
using System.Collections;
public class FollowTUIO_RGBParticles : MonoBehaviour {
GameObject[] repulsors;
GameObject closestRepulsor;
public float repulsionCutoff = 10f;
ParticleSystem[] ps;
float x;
float z;
Vector3 addedForce;
void Update () {
GameObject repulsor = getClosestRepulsor();
applyForce(repulsor);
}
void applyForce(GameObject repulsor)
{
if(repulsor == null)
{
applyConstantRandomForce();
}
else
{
Vector3 difference = repulsor.transform.position - transform.position;
float sqrDiff = difference.sqrMagnitude;
float targetMass = repulsor.rigidbody.mass;
rigidbody.AddForce( difference / -sqrDiff * targetMass);
rigidbody.velocity = vectorClamp(rigidbody.velocity, 1f);
}
}
void applyConstantRandomForce()
{
//check to see if vector is beyond range of -1 to 1. if so, reverse direction of random addition by making it a negative number
if (addedForce.x > .01 || addedForce.x < -.01)
{
x *= -1;
}
if (addedForce.z > .01 || addedForce.z < -.01)
{
z *= -1;
}
addedForce = new Vector3(addedForce.x + x, 0f, addedForce.z + z);
addedForce = vectorClamp(addedForce, 1.5f);
constantForce.relativeForce = addedForce;
//rigidbody.velocity = vectorClamp(rigidbody.velocity);
}
Vector3 vectorClamp(Vector3 curVelocity, float clampAmount)
{
Vector3 clampedVelocity = Vector3.ClampMagnitude(curVelocity, clampAmount);
return clampedVelocity;
}
GameObject getClosestRepulsor()
{
repulsors = GameObject.FindGameObjectsWithTag("Repulsor");
float distance = repulsionCutoff;
Vector3 position = gameObject.transform.position;
foreach (GameObject repulsor in repulsors)
{
Vector3 diff = (repulsor.transform.position - position);
float curDistance = diff.sqrMagnitude;
//find nearest repulsion point
if(curDistance < distance)
{
closestRepulsor = repulsor;
distance = curDistance;
}
}
return closestRepulsor;
}
}