- Home /
How to prevent continuous spinning while aiming at the screen's center?
I am developing a simple 3rd person weapon system. A target gameobject is positioned in the center of the screen using ScreenToWorldPoint on the current camera. The character rotates towards this target via a Quaternion.Slerp when the aim button is held down. The problem is that because the camera is following the rotation of the character and the target positions itself in the center based on the camera it creates an infinity spinning effect; whereby the character rotates to face the target, which rotates the camera following the character, which moves the target since it is not in the center of the camera's screen anymore! How should I resolve this?
The second part of my question is a similar case. While aiming I would like to enable a "Mouse Look" component so that the player is able to "free aim" by moving the mouse. Since this rotates the entire character, it of course causes the same spinning effect as described above since the camera and target try to adjust to the characters rotation causing infinite rotation. What would be the best way to approach this?
Perhaps not making the Camera a child of the player would help.
The camera isn't actually a child as it is not parented to anything. It is using the smooth follow script to follow the character around.
Why is the target positioning itself based on the camera? Why does the target move at all unless its trying to attack the player? What do you mean by A target gameobject is positioned in the center of the screen using ScreenToWorldPoint on the current camera? Why are you implementing it that way? I've done some 3rd person controls, attack systems, enemy AI, never had this problem. Unless I am completely misunderstanding what you mean.
The target gameobject is where the character will be ai$$anonymous$$g towards, it is basically a visual representation of the center of the screen (like a reticule). I use the following line to position the target in the center of the screen:
transform.position = currentCamera.ScreenToWorldPoint(new Vector3(Screen.width/2, Screen.height/2, distance));
This is obviously camera dependent, since the position and rotation of the camera will change what the center of the screen is. In other words, if the camera is rotated 90 degrees on the y axis, the position of the center of the screen will be different to if the camera was rotated 90 degrees on the x axis. Of course if there's a better way to do the above I am open to suggestions :)