Find Mouse co-ordinates on click in a 2d environment

Basically I am attempting to find the x,y coordinates of the mouse cursor when clicking the left mouse button, the reason for this is I have a character with moves along the 2d plane and I want to be able to fire projectiles toward the cursor originating from the character model.

As far as I know the best option is to use ray trace but im not 100% sure how to go about doing so.

Thanks in advance

You’re going to want to make sure that both the actorObject’s coordinates and the mouse coords are occupying the same coordinate space. Input.mousePosition returns screen coordinates and your game actors position will be in world coordinates. So I imagine you’re going to want to either do a raycast against a plane established from your character with Camera.ScreenPointToRay or you’re just going to want to translate the screen coordinates to world coords with Camera.ScreenToWorldPoint. I’m not entirely sure what your game looks like so I can’t really say what will give you the coordinates you want as lots of people say they are making a “2d” game but are actually using all 3 dimension of depth inside the engine and just restricting character and object motion to two axes.

Once you’re gotten the cursors position in world space coordinates you should be able originate objects from the transform of the players character object and throw them and the location of the cursor.

Find X and Y mouse coordinates, calculate the distance between the character that will shot and the mouse, instantiate the projectile, use deltaTime to make it move smoothly to the distance vector.

For the mouse, have a look at Input.mousePosition. To calculate the distance use a Vector2, something like “distance = Vector2(transform.position, Input.mousePosition);”.

Input.mousePosition: Unity - Scripting API: Input.mousePosition

Here is it:

var distance;
var smooth: float = 0.5

function Update()
{
    if (Input.GetButtonDown("Fire1")) {
        distance = Vector2(transform.position, Input.mousePosition);

        transform.Translate(distance, smooth);
    }
}

Or something like that, this is only an example, it doesn’t really work.

if (Input.GetMouseButtonDown(0))
{
var pos = Input.mousePosition;
pos = Camera.main.ScreenToWorldPoint(pos);

    var q = Quaternion.FromToRotation(Vector3.up, pos - transform.position);
    Rigidbody2D go = Instantiate(bulletPrefab, transform.position, q) as Rigidbody2D;
    go.rigidbody2D.AddForce(go.transform.up * 500);
}