Hi, Im using Unity’s Stealth Game code to manage my character’s movement and I’ve implemented an orbit camera.
The problem is that the character always moves based on the global Z axis, so if I move the camera around pressing the forward key moves the char based on its initial orientation and not the camera’s.
Here’s the script Im using. Im thinking I need to make the direction of movement relative to the camera, but Im not sure how.
Any pointers would be greatly appreciated.
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour
{
// Variables
public float turnSmoothing = 15f; // A smoothing value for turning the player.
public float speedDampTime = 0.1f; // The damping for the speed parameter
private Animator anim; // Reference to the animator component.
// Functions
void Awake()
{
anim = GetComponent<Animator>();
}
void FixedUpdate()
{
// Cache the inputs.
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
MovementManagement(h, v);
}
/////////////////////////////////////////////CHARACTER MOVEMENT/////////////////////////////////////////
void MovementManagement (float horizontal, float vertical)
{
// If there is some axis input...
if(horizontal != 0f || vertical != 0f)
{
// ... set the players rotation and set the speed parameter to 5.3f.
Rotating(horizontal, vertical);
anim.SetFloat("Speed", 5.3f, speedDampTime, Time.deltaTime);
}
else
// Otherwise set the speed parameter to 0.
anim.SetFloat("Speed", 0);
}
void Rotating (float horizontal, float vertical)
{
// Create a new vector of the horizontal and vertical inputs.
Vector3 targetDirection = new Vector3(horizontal, 0f, vertical);
// Create a rotation based on this new vector assuming that up is the global y axis.
Quaternion targetRotation = Quaternion.LookRotation(targetDirection, Vector3.up);
// Create a rotation that is an increment closer to the target rotation from the player's rotation.
Quaternion newRotation = Quaternion.Lerp(rigidbody.rotation, targetRotation, turnSmoothing * Time.deltaTime);
// Change the players rotation to this new rotation.
rigidbody.MoveRotation(newRotation);
}
}