Draw a line to the mouse position, regardless of the cameras rotation.

Hi guys,

I have what I think is, but hope is not. a complicated question.

In my 2D game - the player is capable of rotating the camera around his or her Z rotation. I would like to know. where the mouse is no mater what rotation the player has on his or her camera.

at the moment I draw a line to the mouse position by doing the following:

var pos = mainCamera.WorldToScreenPoint(transform.position);
Vector3 dir = Input.mousePosition - pos;
var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.back); // can rotate an abject if I so please.

Debug.DrawRay(transform.position, Input.mousePosition - pos, Color.cyan);

this works perfectly if I am at 0 on the z rotation of the camera. However as soon as I rotate the camera it start to marks a wrong area, and when I reach 180 degree of rotation it is marking the opposite location. so definately related.

my question is how do I make it always draw a line to my mouse, no matter what z rotation the camera is in.

any help would be greatly appreciated as I cannot seem to find any information on this anywhere.

thanks a ton!

either you use Camera.ScreenToWorldPoint() which will be updated with the movement of camera. (but this is the inverse and goes from screen to world)

either you parent your object with the camera (and it will move along the camera)