I hope I can explain this properly. Imagine a 3d world, in it is a plane as ground to stand on, and a character standing upright on top of it. Also, a camera, upright, elevated and pitched down to see the character.
I want to move {using Transform.Translate()} the character forward along the plane in reference to the camera’s forward, but technically since the camera is pitched or angled downwards, the camera’s forward is also at angle, and the character would sink into the ground while moving forward.
How do I get that forward direction vector relative to the direction the camera is facing? I am very lost with the solutions considering the difference between Quaternion and Vector3. Is there a way to convert Quaternions to Vector3 and vice versa? Ill post an image trying to illustrate the idea, and my code.
my code:
using UnityEngine;
using UnityEngine.InputSystem;
public class Character : MonoBehaviour
{
#region References
Camera cam;
#endregion References
#region Components
#endregion Components
#region Movement
bool canMove = true;
Vector2 inputDirection;
[SerializeField] float moveSpeed = 5.0f;
#endregion Movement
private void Start()
{
cam = Camera.main;
}
void Update()
{
Move(inputDirection);
}
public void OnMove(InputAction.CallbackContext context)
{
inputDirection = context.ReadValue<Vector2>();
}
private void Move(Vector2 direction)
{
if(!canMove) return;
// Sideways Movement
Vector3 moveSideways = cam.transform.right * direction.x;
//Forward Movement
Quaternion pitchAngle = new Quaternion(cam.transform.rotation.x - Quaternion.identity.x, 0, 0, 0);
Vector3 moveForward = pitchAngle * cam.transform.forward * direction.y;
Vector3 moveVector = moveSideways + moveForward;
transform.Translate(moveVector * moveSpeed * Time.deltaTime, Space.World);
}
}