- Home /
How can I get a Capsule to move and rotate in the direction the cam is facing?
Hey, I cannot figure out how to make the player rotate in the same direction on the Rotation Y constraint from rigidbody. I have a script that unity has in their wiki, http://wiki.unity3d.com/index.php/SmoothMouseLook and I don't know how to implement it.
Example 1: most fps games have the ability to look through the players eyes, that is what I want. With the script referenced above, I can rotate the camera. But what I want is for the Player to move along the X, and Z, axis depending on where the eyes/Camera are looking. I created two scripts. One is called "CustomFPSCameraMove" (which uses the script referenced above" and the other is called "CustomFPSCapsuleMove" and this is the one I want to move the player('Capsule') along camera Y Rotation so I can move back, forwards, left, and right.
Answer by Link17x · Mar 14, 2020 at 11:36 PM
FPS games tend to hide the mouse cursor and rotate the camera (player perspective) towards whichever direction the mouse is moved. Then move your player using the usual horizontal and vertical inputs (typically WASD).
public class MouseCursor : MonoBehaviour
{
private void Awake()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
public void ToggleMouse(bool show)
{
Cursor.lockState = show
? CursorLockMode.None
: CursorLockMode.Locked;
Cursor.visible = show;
}
Then control your camera rotation based on the mouse position. The camera might need to be a child object of an empty game object that acts as a pivot.
[SerializeField] private Gameobject cameraPivot;
[SerializeField] private float MouseSensitivity = 10;
private void CameraControl()
{
// Make sure the mouse position is within our screen boundaries
var screenRect = new Rect(0, 0, Screen.width, Screen.height);
if (!screenRect.Contains(Input.mousePosition))
return;
// Store a reference to the mouse X and Y position and control the sensitivity
var vertical = Input.GetAxis("Mouse Y") * Time.deltaTime * MouseSensitivity;
var horizontal = Input.GetAxis("Mouse X") * Time.deltaTime * MouseSensitivity;
// Rotate the camera pivot on the X-axis only
// Rotate the player on the Y-axis only
cameraPivot.transform.Rotate(-vertical, 0, 0);
transform.Rotate(0, horizontal, 0);
// Set a limit of how far the camera can turn on the X and Y-axis
// to prevent 360 rotation
var local = cameraPivot.transform.localEulerAngles;
if (local.x <= 340 && local.x >= 90)
{
cameraPivot.transform.localEulerAngles = new Vector3(340, 0, 0);
}
if (local.x >= -45 && local.x <= 120)
{
cameraPivot.transform.localEulerAngles = new Vector3(0, 0, 0);
}
}
This script/method will need to be on the player. I have no idea what you will need/want the sensitivity to be set to, just play around with it in the inspector.