- Home /
find the angle to rotate the gun to face mouse point with its barrel
Hi, it's my first question here. I couldn't find the answer anywhere, so after searching through Internet and not finding anything I finally gave up. Maybe someone will help. I have a problem with my weapon rotation script trying to face mouse pointer.
Basically, what I have is weapon object with fire point object as a child of this weapon object. Fire point is placed on gun barrel sprite. I want to rotate the weapon to make its fire point face mouse point, as opposite to weapon's origin facing mouse (there are so many guides to do this..).
My best approach so far is using regular rotating script based on Atan2, and it works only to certain degree. And by that I mean, that when I have my mouse pointer far from weapon, then everythings seems ok, but then when I hover near, the weapon starts acting weird, shaking and what not. Here's the code:
Vector2 mousePosition = camera.ScreenToWorldPoint(Input.mousePosition);
Vector2 distance = mousePosition - (Vector2)weaponTransform.position;
float angle = Mathf.Atan2(distance.y, distance.x) * Mathf.Rad2Deg;
//if facing left
if(characterTransform.localScale.x < 0){
angle = -angle + 180;
}
weaponTransform.rotation = Quaternion.Euler(0, 0, angle);
Debug.DrawRay(firePointTransform.position, distance, Color.red);
Answer by Socapex · Jun 21, 2015 at 11:26 AM
transform.LookAt, Vector3.RotateToward, Quaternion.RotateTowards all seem like good options. Remember you can change your rotation anchor to fit the object. Also, getting "weird things" is inevitable when the mouse will get close. You can simply disable rotations in a close radius around your gun. Or at least do something elegant when mouse is close.