I have a simple movement script for a Rigidbody.
It gets “moveDirection” based on keyboard input. Then the script takes in a CameraTransform and modifies moveDirection based on the Camera direction, making it so that Player moves in the direction that the Camera is pointing. This is all fine.
The problem I’m having is that I want to also rotate Player rigidbody (around the Y axis) based on the Player’s horizontal mouse movements (which, by the way, change Camera angle).
There is a //Rotation code block that accomplishes this task perfectly IF the Player rigidbody moves by AddForce. However, if I try to make rigidbody move by AddRelativeForce, the rigidbody ends up moving in seemingly random directions.
I understand that AddRelativeForce works based on local coordinates, and that AddForce works based on world coordinates. However, I just cannot seem to find any solution for this.
My question is: How can I modify the //Rotation code so that it works with AddRelativeForce?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HumanoidLandController : MonoBehaviour
{
//Input
public float horizontalInput;
public float verticalInput;
public Vector3 moveDirection;
public bool MoveIsPressed;
//Camera and Rotation
public Transform cameraTransform;
public float rotDegPerSecond = 720f;
public Quaternion targetRotation;
//Movement
[SerializeField] Vector3 _playerMoveInput = Vector3.zero;
[SerializeField] Vector3 _playerCalculatedForce = Vector3.zero;
[SerializeField] float _movementMultiplier = 30.0f;
Rigidbody _rigidbody = null;
private void Awake()
{
_rigidbody = GetComponent<Rigidbody>();
}
public void Update()
{
horizontalInput = Input.GetAxis("Horizontal");
verticalInput = Input.GetAxis("Vertical");
moveDirection = new Vector3(horizontalInput, 0.0f, verticalInput).normalized;
//modify movedirection to move towards camera rotation
moveDirection = (Quaternion.AngleAxis(cameraTransform.rotation.eulerAngles.y, Vector3.up) * moveDirection).normalized;
if (moveDirection != Vector3.zero)
{
MoveIsPressed = true;
}
else
{
MoveIsPressed = false;
}
}
private void FixedUpdate()
{
_playerMoveInput = moveDirection;
_playerCalculatedForce = _playerMoveInput;
_playerCalculatedForce = _playerCalculatedForce * _movementMultiplier;
_playerCalculatedForce *= _rigidbody.mass;
_rigidbody.AddRelativeForce(_playerCalculatedForce, ForceMode.Force);
//_rigidbody.AddForce(_playerCalculatedForce, ForceMode.Force);
//Rotation
if (MoveIsPressed)
{
targetRotation = Quaternion.LookRotation(moveDirection);
targetRotation = Quaternion.RotateTowards(transform.rotation, targetRotation, rotDegPerSecond * Time.deltaTime);
_rigidbody.MoveRotation(targetRotation);
}
}
}