- Home /
Rigidbody movement in direction of camera?
I'm trying to make a RigidBody player move in the same direction the camera is facing. I used the good old "RigidBodyFPSWalker" script, but this makes the player move in its own forward direction and not the cameras (everytime I push up in the joystick it must go in the forward direction of the camera). How can I change the famous script in such way that i rotate the player accordingly and move in the direction of the camera? I'm guessing this RigidBodyFPSWalker is not the ideal since my game is third person :| Thanks in advance.
Answer by Llama_w_2Ls · Aug 06, 2020 at 07:44 AM
bean.transform.rotation = Quaternion.Euler(0, transform.eulerAngles.y, 0); //Locks the y rotation of the player to the camera's y rotation
transform.position = new Vector3 (bean.transform.position.x, bean.transform.position.y + 0.5f, bean.transform.position.z); //Moves the camera with the player
Since the rigidbody player is moving in its own direction, the only thing you have to do is rotate the player with the camera instead, so that the forward direction matches the camera's viewpoint. bean
is the player and this code is attached to the main camera
hmm i was looking for something to change only on the players script.. the camera only follows the player on a fixed rotation, and is up to the user to rotate the camera with another joystick. I tried adding your first line to the player's script in Update method but doesn't work.
Sorry, this was based on the assumption that you had a camera script as well. In my camera script, the camera is parented to the player and consists of code to rotate the Player, as well as the camera. public float $$anonymous$$ouseSensitivity = 500f;
public Transform PlayerBody;
float Xrotation = 0f;
public FloatingJoystick floatingJoystick;
// Update is called once per frame
public void Update()
{
float $$anonymous$$ouseX = floatingJoystick.Horizontal * $$anonymous$$ouseSensitivity * Time.deltaTime; //Input.GetAxis("$$anonymous$$ouse X")
float $$anonymous$$ouseY = floatingJoystick.Vertical * $$anonymous$$ouseSensitivity * Time.deltaTime; //Input.GetAxis("$$anonymous$$ouse Y")
Xrotation -= $$anonymous$$ouseY;
Xrotation = $$anonymous$$athf.Clamp(Xrotation, -90f, 90f);
transform.localRotation = Quaternion.Euler(Xrotation, 0f, 0f);
PlayerBody.Rotate(Vector3.up * $$anonymous$$ouseX);
}
Im also using the free joystick pack on the asset store for the floatingJoystick component.