Find mouse position relative to Object/ set Object zero pos to other object (2D aimer follows mouse and rotates around player)
I want to make an crosshair/aimer that will be a set distance away from the player but will rotate around them to match the mouse position. The player would be able to move around and have the aimer rotate to match the mouse position but sit right on the mouse, staying in a set radius around the player. here is my code that works, but in a wrong way:
public void Movement()
{
curserPosition = Input.mousePosition;
curserPosition = mainCamera.ScreenToWorldPoint(curserPosition); // gets mouse position
aimerAngle = player.transform.eulerAngles.z * Mathf.Deg2Rad; //get player Z rotation
gameObject.transform.position = new Vector2(2f * Mathf.Cos(aimerAngle), 2f * Mathf.Sin(aimerAngle)); // calculates x,y
}
This actually work how I want it to where it makes the aimer rotate with the mouse, (in another script I have the player always facing the mouse) using the players Z rotate axis. But it rotate around the world's 0,0 point, not the player. When I make it a child of the player and use gameObject.transform.localPosition instead of gameObject.transform.position, it acts very odd, too hard for me predict what is really happening to describe but it basically follows in the player's "radius" but isn't "following"/rotating with the mouse properly.
If I had to guess, I think I need to do one of two things, get the mouse position in relation to the player instead of the screen so maybe the localPosition would work, or find out how to actually set the 0,0 for the aimer on the player even as they move, which would probably make the above code work too.
Any thoughts?
My real goal though is make the curser "bounce" in a "line" between the player and a set distance to the mouse as they both move. if you could possible elaborate on that as well, that could help but first things first, lol
Answer by yoj346 · Oct 03, 2021 at 11:16 PM
Turns out I was pretty close, I just needed to save the cos/sin changes to a vector then add it to the "player's" position saved as a vector, then make it the gameObject's position.
curserPosition = Input.mousePosition; //get mouse input
curserPosition = mainCamera.ScreenToWorldPoint(curserPosition); // gets mouse position
aimerAngle = player.transform.eulerAngles.z * Mathf.Deg2Rad; //get player Z rotation
curserMovement = new Vector2(2f * Mathf.Cos(aimerAngle), 2f * Mathf.Sin(aimerAngle)); // calculates x,y
gameObject.transform.position = new Vector2(curserMovement.x + player.transform.position.x, curserMovement.y + player.transform.position.y); //player pos + cos/sin pos