Hi everybody.
I’m making a small game as part of the Junior Programmer pathway with a camera that is fixed above the player and it is not rotating.
I’ve made my character to look in the direction of the cursor. I’ve also made it move around the level, using world space (so no matter where my character looks - pressing down will always make the character go down).
I’ve downloaded the human model with some animations and I’ve configured them to move smoothly based on my horizontal/vertical input. And it all works well as long as my character looks forward. But when I rotate the character - it starts moonwalking (which is kinda funny, but that’s not what I’m looking for).
public class PlayerController : MonoBehaviour
{
public float movementSpeed = 1;
private Animator animator;
// Start is called before the first frame update
void Start()
{
animator = GetComponent<Animator>();
}
// Update is called once per frame
void Update()
{
LookAtMouse();
MovePlayer();
//if(Input.GetKeyDown(KeyCode.Mouse0))
// Attack();
}
// gets input on axis and applies to players coordinates
void MovePlayer()
{
//get input
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");
//apply input to move player
transform.Translate(Vector3.forward * movementSpeed * verticalInput * Time.deltaTime, Space.World);
transform.Translate(Vector3.right * movementSpeed * horizontalInput * Time.deltaTime, Space.World);
//animation based on movement
if (verticalInput != 0 || horizontalInput != 0)
{
animator.SetBool("Moving", true);
animator.SetFloat("Horizontal", horizontalInput);
animator.SetFloat("Vertical", verticalInput);
}
else if (verticalInput == 0 && horizontalInput == 0)
animator.SetBool("Moving", false);
}
void LookAtMouse()
{
//creating a ray and detecting where it hits something
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
int layerMask = 1 << 3;//3rd layer is set to be ground
if (Physics.Raycast(ray, out hit, 1000, layerMask)) //check if there is a spot to look at on the ground
{
Vector3 positionToLookAt = hit.point;//get the spot to look at
transform.LookAt(positionToLookAt);//look at the spot
transform.rotation = Quaternion.Euler(0, transform.rotation.eulerAngles.y, 0);//remove other rotations, so the player only rotates on the Y axis
}
}
As you can see at the lines 34 and 35 - I’m passing my input as parameters to my animator. But that input is always in the world space. I need to somehow calculate how much Horizontal and Vertical movement I should pass to the animator, so that the animations are played in correlation to the player’s rotation. How can I do that?
Or maybe there is a better way to play those animations, that I’m not aware of?
Thanks!