Created
April 9, 2015 14:51
-
-
Save twobob/0ab2a30ecb92c4627c0d to your computer and use it in GitHub Desktop.
PlaceParticles.cs Place Unity particles individually.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using UnityEngine; | |
using System.Collections; | |
public class PlaceParticles : MonoBehaviour | |
{ | |
public ParticleSystem tree; // plural. like sheep. | |
public Transform ObjectToPopulateWithParticles; | |
// a flatish square mesh is a good idea since our helper will take a | |
// random point sample in the negative Y on a pre-defined square. | |
// You can write better helpers... | |
// we will just start a loop until we have our particles ready to reposition | |
void Start() | |
{ | |
StartRepeatingCheckForParticleCount(); | |
} | |
void CreateTreesFromParticles() | |
{ | |
// should be 1000 in my case... | |
int partNum = tree.particleCount; | |
if (partNum == 0) | |
return; | |
// make a list, of the same length | |
ParticleSystem.Particle[] ParticleList = new ParticleSystem.Particle[partNum]; | |
tree.GetParticles(ParticleList); | |
for (int i = 0; i < ParticleList.Length; ++i) | |
{ | |
// "5" is the tree sprite height offset we want, ignore it. change it for your tree height | |
// GenerateRandomLocationInArea and ShootRayReturnParticlePosition | |
// just find a place in a block and shoot a ray down, | |
// nothing fancy, just puts it on the floor. | |
Vector3 newPlace = PlaceParticles.ShootRayReturnParticlePosition(PlaceParticles.GenerateRandomLocationInArea(ObjectToPopulateWithParticles)) + (Vector3.up * 5); // magic number erk! | |
// actually assign the location to the particle in the list | |
ParticleList[i].position = newPlace; | |
} | |
//actually assign the particles, with new positions, back to the system | |
tree.SetParticles(ParticleList, partNum); | |
CancelInvoke("CreateTreesFromParticles"); | |
} | |
void StartRepeatingCheckForParticleCount() | |
{ | |
InvokeRepeating("CreateTreesFromParticles", 0, 0.02F); | |
} | |
// helper bits | |
// 256 is my "magic" block size | |
public static Vector3 GenerateRandomLocationInArea(Transform chosenparent) | |
{ | |
return new Vector3(Random.Range(10, 246) + chosenparent.position.x, 35f, | |
Random.Range(10, 246) + chosenparent.position.z); | |
} | |
public static Vector3 ShootRayReturnParticlePosition(Vector3 location) | |
{ | |
Vector3 targetPosition = Vector3.zero; | |
RaycastHit hit; | |
if (Physics.Raycast(location, -Vector3.up, out hit)) // ugh. | |
{ targetPosition = hit.point; } | |
return targetPosition; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment