Controlling player with mouse
I'm making a top down 2.5D game where the player controls the character's aiming with the mouse.
void Update () {
Vector3 mouseWorldPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition + Vector3.forward * 10f);
float angle = AngleBetweenPoints(transform.position, mouseWorldPosition);
Vector3 mousePos = Input.mousePosition;
mousePos.x -= Screen.width / 2;
mousePos.y -= Screen.height / 2;
//To make mousePos relative to transform
mousePos += transform.position;
angle = Vector3.Angle(mousePos, Vector3.up);
//For 360 degree angle
if (mousePos.x > 0)
angle = 360 - angle;
transform.rotation = Quaternion.Euler(0, -angle, 0);
}
float AngleBetweenPoints(Vector2 a, Vector2 b) {
return Mathf.Atan2(a.y - b.y, a.x - b.x) * Mathf.Rad2Deg;
}
Now this works when my character is in the center of the screen however when I move my character, this doesn't work anymore. The problem is that no matter where my character's position is, the controls will always pretend like the character is in the center of the screen. So if my character is on the left of the screen and I move the mouse around the character it doesn't work however if I move the mouse around the center of the screen then it works. I think the problem is with this line:
mousePos.x -= Screen.width / 2;
mousePos.y -= Screen.height / 2;
What this does is make the mouse position relative to the center of the screen which is what I don't want. I instead want the mouse position to always be relative to where ever my character is. Does anyone know what the problem is?
Your answer
![](https://koobas.hobune.stream/wayback/20220612111908im_/https://answers.unity.com/themes/thub/images/avi.jpg)