- Home /
2D : Rotation of Object With x-y Axis
I am developing 2D shooting game in that I have plane game object with x axis on right and y axis on top position. Now on bottom side of the plane I have one object which I want to rotate in mouse position.
Here is my code:
function Update () {
var mousePos = Input.mousePosition;
mousePos.z = 20.0f; //The distance from the camera to the player object
var lookPos : Vector3 = Camera.mainCamera.ScreenToWorldPoint(mousePos);
lookPos = lookPos - mousePos;
var angle : float = Mathf.Atan2(lookPos.y, lookPos.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}
But here angle becomes so large . And it is rotating on x-y axis but not with mouse position. So what do i need to do? Please help me to solve my problem.
Thank you for your support and help.
Answer by Ekta-Mehta-D · Mar 08, 2013 at 06:31 AM
function Update ()
{
mouse_pos = Input.mousePosition;
mouse_pos.z = 5.23; //The distance between the camera and object
object_pos = Camera.main.WorldToScreenPoint(target.position);
mouse_pos.x = mouse_pos.x - object_pos.x;
mouse_pos.y = mouse_pos.y - object_pos.y;
angle = Mathf.Atan2(mouse_pos.y, mouse_pos.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(Vector3(0, 0, angle - 90));
}
I got my solution.
Answer by robertbu · Mar 08, 2013 at 05:37 AM
Assuming this is attached to the object that is rotating, line 5 should be:
lookPos = lookPos - transform.position;
but i want that if my mouse is anywhere in plane , then i want my object to face my mouse position in plane. Here it is not like this. It is not following my mouse cursor.
Try it. I just tested it to make sure I was giving an accurate answer, and it worked just fine for me. It will follow it anywhere on the plane. The purpose of that line is to make the vector used to calculate the angle relative to the object rotating. If this doesn't do what you want, then you need to provide a much clearer description of the problem.
i was having problem with angle which i have set. now its working perfactly. thanks for your reply.
Your answer
Follow this Question
Related Questions
2D Rotate object so y axis faces other object 1 Answer
2D Game - Y axis rotation (left - right) 2 Answers
Rotating an object on Z axis while moving 1 Answer
Disabling the Z axis? 1 Answer
Converting Android Axis to Unity Axis 0 Answers