- Home /
Question by
omergolan38 · Dec 02, 2021 at 09:57 PM ·
c#rotationmousepositionanglestrigonometry
C# Code Understanding - Trigonometry + Angles - Object rotating around player and facing mouse direction
//Problem: I do not understand how this code works and I require an
explanation;
public GameObject player;
private Vector3 v3Pos;
private float angle;
private readonly float distance = 0.16f;
private void Update()
{
v3Pos = Input.mousePosition;
v3Pos.z = (player.transform.position.z -
Camera.main.transform.position.z);
v3Pos = Camera.main.ScreenToWorldPoint(v3Pos);
v3Pos -= player.transform.position;
angle = Mathf.Atan2(v3Pos.y, v3Pos.x) * Mathf.Rad2Deg;
if (angle < 0.0f) { angle += 360.0f; }
transform.localEulerAngles = new Vector3(0, 0, angle);
float xPos = Mathf.Cos(Mathf.Deg2Rad * angle) * distance;
float yPos = Mathf.Sin(Mathf.Deg2Rad * angle) * distance;
transform.localPosition = new Vector3(player.transform.position.x +
xPos * 4, player.transform.position.y + yPos * 4, 0);
}
Hi, I found this code in a video which makes an object (like a gun) rotate around the player and follow the mouse simultaneously but I don't understand how it works... could anyone tell how it works, step by step? also, I don't know where the video is at anymore but I will find it if necessary.
Comment
This is a bit of a bad implementation. Are you sure you want to use it?
You can implement most of this behaviour with much less code (you can actually implement this without writing any code)
Either way unless theres a good reason you can probably rely on parenting for the object/ camera rotating with the players look position and then just use a normal MouseLook implementation. There are probably thousands of examples online