Question by
DCA123 · Jan 25, 2016 at 04:44 AM ·
2d gameparticle system
How do I set the width of a particle system using code in Unity 2D? (C#)
In Unity 5, using Unity 2D, I would like to have a particle system span the entire, or partial, width of my camera. Keeping in mind that distance may change based on device screen resolution, how can I do this in code (C#)?
Thanks!
Comment
Is Camera.main.pixelWidth; Camera.main.pixelHeight; What you're looking for..? o.O
They are in pixels and are not what he needs, 'cause it's not the world space.
Answer by incorrect · Jan 25, 2016 at 06:00 AM
using UnityEngine;
using System.Collections;
public class ParticleSystemFitter : MonoBehaviour
{
void Start ()
{
ParticleSystem pSystem = GetComponent<ParticleSystem>();
//Just checking if everything's OK
#region checks
if(pSystem == null)
{
Debug.LogError(name + " is missing Particle System!");
return;
}
Camera camera = Camera.main;
if(!camera.orthographic)
{
Debug.LogError("Camera is not in orthographic mode!");
return;
}
if(pSystem.shape.shapeType != ParticleSystemShapeType.Box)
{
Debug.LogError("Particle system is not in a box shape!");
return;
}
#endregion
//calculating camera's viewport ratio
//if you don't cast those ints to floats, you'l get a bit different result 'cause int's division is different
float ratio = (float)camera.pixelWidth / (float)camera.pixelHeight;
//calculating particle box based on camera's orthorgaphic size (which is in world space)
//and camera's veiwport ratio;
//multiplying by 2 'cause orthorgaphic size is the half of camer's viewport height
Vector3 particleBox = new Vector3(2f * ratio * camera.orthographicSize, 2f * camera.orthographicSize, 1f);
//applying this box to the particle system
ParticleSystem.ShapeModule shape = pSystem.shape;
shape.box = particleBox;
}
}
Any questions?
Your answer
