- Home /
Making a sprite rotate towards mouse when sprite is not centered on screen
Hello. I have been looking through the forums but not found anything that quite solves my problem.
I have a sprite that is rotating around the main character. The mouse position is changing its rotation so it always points towards the mouse. This works all fine and dandy but heres the problem:
It only works smoothly when the player is centered on the screen. I want it to always point towards the mouse even if the player is not centered.
Here is the code I have for handling the rotation:
Vector2 target = new Vector2 (shieldCenter.transform.position.x, shieldCenter.transform.position.y); //vector for transforming the shield to the target, aka the player
Vector3 mousePos = new Vector3(Input.mousePosition.x, Input.mousePosition.y,10); //where the mouse is on the screen
Vector3 lookPos = Camera.main.ScreenToWorldPoint(mousePos); //position for the shield to look towards
lookPos = lookPos - shield.transform.position; //make the shield look towards the mouse
angle = Mathf.Atan2(lookPos.y, lookPos.x) * Mathf.Rad2Deg; //turn radians to degrees
shield.transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward); //transform the rotation of the shield towards the mouse
shield.transform.position = target; //set the position of the shield to the target
the shields pivot is centered while the sprite itself is drawn on the right side of it. Which allows it to rotate around the player. The shields pivot is set to the center of the player by code.
Here's a screenshot of my game so you might have a better idea of what I am trying to achieve:
On this example the player is located on the left side of the screen. Which messes up the rotation if i am trying to rotate the shield on the players left side. If the camera was centered on the player it would have worked perfectly.
Answer by Dr-Orange · Nov 13, 2016 at 11:46 AM
Make an empty game object then put it on the centre of the character. call it "axis" attach the script below to it then get your shield component and attach it and a child of your axis.
void Update () {
Vector2 mouse = Camera.main.ScreenToViewportPoint (Input.mousePosition); //Mouse position
Vector3 objpos = Camera.main.WorldToViewportPoint (transform.position); //Object position on screen
Vector2 relobjpos = new Vector2 (objpos.x - 0.5f, objpos.y - 0.5f); //Set coordinates relative to object
Vector2 relmousepos = new Vector2 (mouse.x - 0.5f, mouse.y - 0.5f) - relobjpos;
float angle = Vector2.Angle (Vector2.up, relmousepos); //Angle calculation
if (relmousepos.x > 0)
angle = 360 - angle;
Quaternion quat = Quaternion.identity;
quat.eulerAngles = new Vector3 (0, 0, angle); //Changing angle
transform.rotation = quat;
}
}