- Home /
Question by
manasseh21 · Jul 27, 2016 at 07:07 PM ·
rotationgameobject
How to rotate object based on mouse position
I'm making a game and in it you are suppose to shoot enemies . So I need the arm to rotate based on the mouse position. So I thought I could calculate the angle by finding the distance from the mouse to the center of the object (with vector2.distance). Then I thought I could find the position from follow to center . After that I divided follow to center by mouse to center(to simulate cos). Then I did acos to find the angle,and then I set the angle to the Z of the rotation.
using UnityEngine;
using System.Collections;
public class Test : MonoBehaviour
{
public Transform center;
public Transform follow;
void Start() {
}
void Update () {
//mouse position
Vector3 mousepos = Input.mousePosition;
//2d positions
Vector2 centpos = new Vector2 (center.position.x,center.position.y);
Vector2 mousepos2d = new Vector2 (mousepos.x,mousepos.y);
Vector2 folpos = new Vector2 (follow.position.x,follow.position.y);
//distances
float hyp = Vector2.Distance (mousepos2d,centpos);
float adj = Vector2.Distance ( folpos,centpos);
//angle calculations
float c = adj / hyp;
float angle = Mathf.Acos (c);
//setting the angle as rotation
Vector3 rotation = new Vector3 (0f,0f,angle);
gameObject.transform.Rotate (rotation);
}
}
But my end result is just my gameobject rotating continuously.
diagram.png
(4.1 kB)
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612085625im_/https://answers.unity.com/themes/thub/images/avi.jpg)