Hello:
We created a Particles class (with its attributes, etc.)
We create X amount of particles (cubes) and store them in an array, aParticles. This will allow us to check/modify values (positions, etc.) of each individual particle.
Now, on our PLAYER (a cylinder), we created a spherical collider. When it collides with one of the particles, this ones (the cubes) should be attracted to the PLAYER.
The code is as follow:
function OnTriggerStay(collision : Collider) {
for(i=0; i<aParticles.length; i++)
{
//Calculate and normalize EACH particle's direction
var dir = aParticles*.cube.transform.position - transform.position;*
dir = dir.normalized;
aParticles_.cube.rigidbody.AddForce(-dir * force);_
}
}
Notice that I instance the particles form the aParticles array, which has a “cube” attribute (which, in fact, has the cube object)
Now, OnTriggerStay, should check the collision every frame and if there are objects inside, do the code I posted (attract the cubes to the PLAYER. The script is attached to the player).
Now, for some reason, if I put many particles (let’s say 20) the game get VERY slow. 20 is nothing. If I put 5, it runs OK.
Could you recommend me something?
EDIT:
Here is a way to do the described behavior without the OnTriggerStay:
* var radius:Number = 10;*
* …*
* (in the Update function)*
* for(i=0; i<aParticles.length; i++)*
* { *
_ var distance = Vector3.Distance(player.transform.position, aParticles*.cube.transform.position);
if (distance < radius) {
var dir = aParticles.cube.transform.position - transform.position;
dir = dir.normalized;
aParticles.cube.rigidbody.AddForce(-dir * force);
}
}*_