Particle Effect to Follow Mouse

Hey guys looking for help to get a particle effect I created in a scene that appears on a mouse click, but I need it to follow the position of the mouse cursor.

Any help is appreciated

Here is my code:

var particle: ParticleEmitter;
var partPos: Vector2;

function Start()
{

var mousePos = Input.mousePosition;
this.renderer.enabled = false;

}

function Update ()
{

var mousePos = Input.mousePosition;
particle.transform.position = mousePos;
Debug.Log(gameObject.transform.position.ToString());
//partPos = mousePos;

}

Thanks a lot!

1 Answer

1

Since Input.mousePosition is a Vector2 from the screen’s coordinate system (distance from the corner of the screen in pixels) and transform.position is a Vector3 from the world’s coordinate system (distance from the origin in generic units) they aren’t interchangeable and will require some calculation to convert one to another.

Going from a world position to a screen position is the easier of the two using Camera.WorldToScreenPoint:

var worldPosition : Vector3 = new Vector3(2,1,4);
var screenPosition : Vector2 = Camera.main.WorldToScreenPoint(worldPosition);

Which is useful for placing GUI elements over objects but not really what you were asking about. So onto converting from screen position to world position; This is a little more complex but still pretty simple. The reason for the added complexity is that there is only one screen point for any given world point, however there are infinite world points for any given screen point: think of a line shooting out from the origin of the camera directly through your mouse cursor infinitely long.

So we have to decide how far we should go on that line before we have our world point. Probably the most common way to do this is by using Physics.Raycast to cast a ray along that line we talked about and when it hits something we’ll use that point as our world point. Camera.ScreenPointToRay allows us to quickly get that imaginary line for use in our script.

var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
var distance : float = Camera.main.farClipPlane;
var hit : RaycastHit = new RaycastHit();
if (Physics.Raycast(ray, hit, distance)) {
    transform.position = hit.point;
}

This method does require that you have something to hit with the ray such as a floor or ground. If not you can add a large box collider to your scene whose top edge is at your “ground” level and is wide/long enough to cover the entire play area.

Hope that gets you started.