Hello, I am very new at unity and here is my problem.
I have an object I would like to move and have him face the direction I am moving to. So or example, I press the left arrow key my character immediately looks at the left and subsquently moves to that direction. The same logic applies to the other directions.
The following code works but the issue here is that it also rotates the axis he is on, as in I press left and the object looks at the left direction but moves “up” instead of going to the left side of the screen. Here just a snippet of what of what I have so far.
You will have collision problems if you don’t apply this through the CharacterController’s Move() function. Here’s one for moving relative to the camera.
public CharacterController charController;
public float moveSpeed = 1f;
public float gravityForce = 9.8f;
void Update()
{
// NOTES
// http://answers.unity3d.com/questions/8444/moving-player-relative-to-camera.html
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
// Get forward (relative to cam)
Vector3 forward = Camera.main.transform.TransformDirection(Vector3.forward);
forward.y = 0f;
forward = forward.normalized;
// Get right
Vector3 right = new Vector3(forward.z, 0f, -forward.x);
// Make a local move direction (right + forward)
Vector3 localMoveDir = (horizontal * right + vertical * forward);
// Turn to face, smooth
if (localMoveDir != Vector3.zero)
{
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(localMoveDir), 10f * Time.smoothDeltaTime);
transform.eulerAngles = new Vector3(0f, transform.eulerAngles.y, 0f);
}
// Diagonal speed clamp
if (localMoveDir.sqrMagnitude > 1f)
localMoveDir = localMoveDir.normalized;
// Gravity
localMoveDir.y = (Physics.gravity * gravityForce * Time.deltaTime).y;
// APPLY MOVE
charController.Move(localMoveDir * moveSpeed * Time.deltaTime);
}
If you want him to move along the regular world axis, then modify the line to this:
// Make a local move direction
Vector3 localMoveDir = new Vector3(horizontal, 0f, vertical);