Question by
Updog97 · Feb 11, 2021 at 05:05 PM ·
cameramovementrigidbodythird person controller
Rigidbody movement relative to third person camera
I'm trying to make a 3rd person game that uses rigidbody movement. I want the player to move relative to the camera position. I'm using CinemachineFreeLook as my third-person camera.
The player object correctly faces the direction the camera is pointing but when I move left, for example, the player faces and moves left relative to the world.
This is what my code looks like:
using UnityEngine;
public class RbController : MonoBehaviour
{
public Transform cam;
public float speed = 5f;
public float jumpHeight = 2f;
public float groundRadius = 0.533f;
public LayerMask ground;
private Rigidbody rb;
private Vector3 input = Vector3.zero;
private bool isGrounded = true;
public Transform groundCheck;
public float turnSmoothTime = 0.1f;
float turnSmoothVelocity;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
isGrounded = Physics.CheckSphere(groundCheck.position, groundRadius, ground, QueryTriggerInteraction.Ignore);
input = Vector3.zero;
input.x = Input.GetAxis("Horizontal");
input.z = Input.GetAxis("Vertical");
if (input != Vector3.zero)
transform.forward = input;
if (Input.GetButtonDown("Jump") && isGrounded)
{
rb.AddForce(Vector3.up * Mathf.Sqrt(jumpHeight * -2f * Physics.gravity.y), ForceMode.VelocityChange);
}
float lookdirection = Mathf.Atan2(input.x, input.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, lookdirection, ref turnSmoothVelocity, turnSmoothTime);
transform.rotation = Quaternion.Euler(0f, angle, 0f);
//Vector3 moveDirection = Quaternion.Euler(0f, lookdirection, 0f) * Vector3.forward;
//move
rb.MovePosition(rb.position + input * speed * Time.fixedDeltaTime);
}
Comment