I’m creating a 3D top-down shooter for my course’s final project and am having trouble getting the player movement to work properly. I want the character to behave as it would in an 2D top-down shooter, where they can move in the cardinal directions relative to the camera (up, down, left, right) plus a combination of these (up-left, down-right, etc.). I have the movement operating normally, but the player should also instantly rotate into the direction they’re moving, somewhat like this video:
I’m able to get the rotation working, but it’s not instantaneous. I’ve been led to Transform.LookAt function, but I don’t think I understand how it works. When I use it, I get wacky behavior. Here’s the closest I’ve gotten.
Hey @raginghobo32907
I just finished the Haunted Jaunt tutorial on Unity Learn. The movement you’re describing is explained on there. Here’s the relevant snippet for you:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SimpleMove : MonoBehaviour
{
public float moveSpeed = 1f;
public float turnSpeed = 20f;
Rigidbody m_Rigidbody;
Vector3 m_Movement;
Quaternion m_Rotation = Quaternion.identity;
void Start()
{
m_Rigidbody = GetComponent<Rigidbody>();
}
void FixedUpdate()
{
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
m_Movement.Set(horizontal, 0f, vertical);
m_Movement.Normalize();
bool hasHorizontalInput = !Mathf.Approximately(horizontal, 0f); // Sets the bool to true if 'horizontal' input is approx 0
bool hasVerticalInput = !Mathf.Approximately(vertical, 0f);
bool isWalking = hasHorizontalInput || hasVerticalInput;
Vector3 desiredForward = Vector3.RotateTowards(transform.forward, m_Movement, turnSpeed * Time.deltaTime, 0f);
m_Rotation = Quaternion.LookRotation(desiredForward);
m_Rigidbody.MovePosition(m_Rigidbody.position + m_Movement * moveSpeed * Time.deltaTime);
m_Rigidbody.MoveRotation(m_Rotation);
}
}