Can't rotate object towards the mouse (2d)

i’m trying to shoot towards the mouse and i’m using this set up
9767181--1399236--upload_2024-4-12_20-2-58.png

the rotate thing has this function that i call every update

private void AimMouse()
    {
        Vector3 cursorPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        Vector2 direction = cursorPos - transform.position;
        float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
        Quaternion rotation = Quaternion.AngleAxis(angle, Vector3.forward);
        transform.rotation = Quaternion.Slerp(transform.rotation, rotation, 1);
        // i've also tryed transform.rotation = Quaternion.Euler(new(0,0,angle)) and
       //Quaternion.angleAxis(angle,Vector3.forward)
    }

but the result is this:
q9j91b

You can short circuit a lot of this just by subtracting the two positions (object from mouse) and setting the result into either the transform.right or transform.up field of the pointer.

Vector2 delta = cursorPos - transform.position;

transform.right = delta;

Change .right to .up perhaps if your pointer points up naturally.

You might want to guard the above code from running if you think delta could be (0,0,0)

1 Like

i’ll try ty for the reply

private void AimMouse()
{
    Vector3 cursorPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    Vector2 direction = cursorPos - transform.position;
    transform.right = direction;
}

it still gives me the same error T^T
i also tryed transform.up

You say this is 2D in your title, but is it X/Y ??

Perhaps it is X/Z and you should be setting the transform.forward?

Generally when you say 2D in Unity you are referring to the X/Y plane.

Vector3 direction=new Vector3(Input.mousePosition.x-Screen.width/2,0,Input.mousePosition.y-Screen.height/2);
transform.right=direction;

yeah X/Y
9767331--1399299--upload_2024-4-12_21-28-39.png
but also the map in 3d cause my classmates made it like that

Well in that case what I wrote above works, so start debugging it.

Maybe you’re not using the transform you think you are.

Print out the two vector inputs, figure it out.

yup it was as you said the problem was that the cam was offset by -18 in the y so all i had to do was to add 18 to the y of the mouse position