# Having projectile face mouse position

I’m trying to create a projectile that will face and move towards the direction of where the mouse was when the player clicked to fire.

I’ve tried a couple of ways to do this but they don’t work very well. This is currently the script I’m using to create and change the rotation of the fireball:

``````void FireBall()
{
Vector2 dir = Input.mousePosition - transform.position;
float angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;

GameObject fireballObject = Instantiate(fireBall, firePoint.transform.position, Quaternion.identity) as GameObject;
{
fireballObject.transform.localScale = new Vector3(1, 1, 1);
fireballObject.GetComponent<FireBall>().ApplyForce(transform.right);
fireballObject.transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
else if(transform.localScale == new Vector3(-1, 1, 1))
{
fireballObject.transform.localScale = new Vector3(-1, 1, 1);
fireballObject.GetComponent<FireBall>().ApplyForce(-transform.right);
fireballObject.transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
}
``````

This is what happens when I test it:

The red circle is where my mouse was when I clicked but as you see, the fireball isn’t facing that direction and I’m not sure why.

Anyone small thing that I also can’t get working is making the projectile move the direction it’s facing.

Could anyone help me?

The problem lies at the very beginning:

``````Vector2 dir = Input.mousePosition - transform.position;
``````

Input.mousePosition gives you the position of your cursor… on the screen. You need to convert that to world space, first.

At a glance, your environment appears to be 2D, so I’ll base my example around that assumption.

A simple conversion of screen coordinates into world position can be done using something like:

``````Vector3 worldMousePosition3D = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 mousePosition = new Vector2(worldMousePosition3D.x, worldMousePosition3D.y);
``````

Then, you can use the result instead, for:

``````Vector2 dir = mousePosition - transform.position;
``````