I’m currently working on a small project to learn, it’s a Twin Stick Brawler of sorts.
So I got this Character with Idle, Walk, Run, Strafe Left, Strafe Right and Backpedal animations. I’ve put those animations in a 2D Freeform Directional Blendtree and then linked the Input.GetAxisRaw(“Horizontal”) and Input.GetAxisRaw(“Horizontal”) vertical to the two Animator parameters. It works great!
This is how the setup is so far:
[GameObject] Player
- [Script] Controls
- [GameObject] CharacterModel
– [Script] LookAtMouse
The problem comes in when I make the character rotate. The LookAtMouse script rotates the CharacterModel so it looks at the mouse position. That obviously breaks the animations as the character could be looking to the right while I press the W-key (which would normally be moving up) and it’ll still play the running-animation while it should be strafing.
I’ve been experimenting with a couple possible solutions but nothing worked out, do you guys have some ideas?
Used code below:
public class Controls : MonoBehaviour
{
public float moveSpeed; //Set in Inspector
public float gravity; //Set in Inspector
private CharacterController controller;
private Animator animator;
private Vector3 moveDirection = Vector3.zero;
void Awake()
{
controller = GetComponent<CharacterController>();
animator = transform.GetChild(0).GetComponent<Animator>();
}
void Update()
{
float h = Input.GetAxisRaw("Horizontal");
float v = Input.GetAxisRaw("Vertical");
animator.SetFloat("X", h);
animator.SetFloat("Y", v);
//Debug.Log("X: " + h + " | Y: " + v);
moveDirection = new Vector3(h, 0, v);
if (moveDirection.magnitude > 1.0f)
moveDirection = moveDirection.normalized;
moveDirection = transform.TransformDirection(moveDirection);
moveDirection *= moveSpeed;
moveDirection.y -= gravity * Time.deltaTime;
Debug.Log("Move: " + moveDirection.ToString());
controller.Move(moveDirection * Time.deltaTime);
}
}
public class LookAtMouse : MonoBehaviour
{
public Camera cam;
public float speed = 20.0f;
void Update ()
{
Plane playerPlane = new Plane(Vector3.up, transform.position);
Ray ray = cam.ScreenPointToRay(Input.mousePosition);
float hitdist = 0.0f;
if (playerPlane.Raycast(ray, out hitdist))
{
Vector3 targetPoint = ray.GetPoint(hitdist);
Quaternion targetRotation = Quaternion.LookRotation(targetPoint - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, speed * Time.deltaTime);
}
}
}