Orbiting Crosshair issue when trying to stop at a specific angle
Hi Guys, I am pretty new here and I recently followed a tutorial to get me onto Game Development again. I have been working on a simple 2.5D game where the main player character is able to shoot spheres for the time being. I have managed to implement a crosshair that rotates around the player and managed to get it to stop when it reaches 90 and -90 degrees using the mouse.
However the issue I am having is when I move the mouse fast the crosshair seems to add more or less rotation which means on the next frames it does not stick to the 90 and -90 degrees I desire.
Image 1 - what I want to happen: Image 1 Image 2 - What happens if I move the mouse fast: Image 2
Code is below: public class CrosshairManager : MonoBehaviour { [SerializeField] private Transform _pivotPosition;
[SerializeField]
public float yOrbit = 0;
[SerializeField]
public float yOrbitOver, _oldAngle, _angle;
[SerializeField]
private bool _goingUp = false, _goingDown = false, _stop = false;
public static Vector3 RotatePointAroundPivot(Vector3 point, Vector3 pivot, Quaternion angle)
{
return angle * (point - pivot) + pivot;
}
// Update is called once per frame
void FixedUpdate()
{
//Work out angle from crosshair position and mouse position
Vector3 crosshairVector = Camera.main.WorldToScreenPoint(transform.position);
crosshairVector = Input.mousePosition - crosshairVector;
_angle = Mathf.Atan2(crosshairVector.y, crosshairVector.x) * Mathf.Rad2Deg;
//Set boolean flags to see if mouse is going up or down
if (_angle > 0)
{
_goingUp = true;
_goingDown = false;
}
else if (_angle < 0)
{
_goingDown = true;
_goingUp = false;
}
//Check if mouse is going up or down and add angle to yOrbit
if (_goingDown && yOrbit > -90)
{
Debug.Log("Going Down");
yOrbit += (_angle);
}
else if (_goingUp && yOrbit < 90)
{
Debug.Log("Going Up");
yOrbit += (_angle);
}
//Check if yOrbit (angle of crosshair) is over 90 and stop it in place
if (yOrbit >= 90.0f)
{
yOrbitOver = yOrbit - 90.0f;
Debug.Log(yOrbitOver);
_angle = _angle + yOrbitOver;
yOrbit -= yOrbitOver;
_stop = true;
}
//Check if yOrbit (angle of crosshair) is below -90 and stop it in place
else if (yOrbit <= -90.0f)
{
yOrbitOver = yOrbit + 90.0f;
Debug.Log(yOrbitOver);
_angle = _angle - yOrbitOver;
yOrbit -= yOrbitOver;
_stop = true;
}
//If within desired angle restraints then set stop to false and allow movement
else
{
_stop = false;
}
//Rotate the corsshair around the pivot point
if (_stop == false)
{
transform.position = RotatePointAroundPivot(transform.position, _pivotPosition.transform.position, Quaternion.Euler(0, 0, _angle));
}
}
}