- Home /
Rotate objects by mouse
I have an object rotating code by mouse position but I have a problem that I move the mouse and the object rotates to the other side.That is, I move the mouse to the right and the object moves to the left.
the code
public class GunScript : MonoBehaviour
{
Vector3 mousePosition;
Vector2 directionMouse;
public Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
mousePosition = Input.mousePosition;
mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
directionMouse = new Vector2(mousePosition.x - transform.position.x, mousePosition.y - transform.position.y);
float angle = Mathf.Atan2(directionMouse.x, directionMouse.y) * Mathf.Rad2Deg + 90f;
rb.rotation = angle;
}
}
Comment
Best Answer
Answer by rage_co · Jul 02, 2021 at 03:04 PM
i think you should just put
rb.rotation = -angle;
Or if it's just a problem with one axis......put a negative sign before the desired axis in the line where you define angle....like
float angle = Mathf.Atan2(- directionMouse.x, directionMouse.y) * Mathf.Rad2Deg + 90f;
or
float angle = Mathf.Atan2(directionMouse.x, -directionMouse.y) * Mathf.Rad2Deg + 90f;
hope this helps!
Your answer
Follow this Question
Related Questions
Rotation of Object on single axis in direction of the mouse position 0 Answers
Slerp/Rotational Problem Query 1 Answer
Object Look At Mouse 2 Answers
Checking if statement in higher frequency 0 Answers
Authoritative Rotation 2 Answers