- Home /
Please resolve my issue with below scripts- Player didn't move left and right
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityStandardAssets.CrossPlatformInput;
public class PlayerMove : MonoBehaviour { public float speed ; float horizontal; float vertical;
Animator anim;
Rigidbody rb;
Vector3 movement;
// Use this for initialization
void Start()
{
anim = GetComponent<Animator>();
rb = GetComponent<Rigidbody>();
}
void MoveHandler()
{
movement = new Vector3(horizontal, 0f, vertical);
horizontal = CrossPlatformInputManager.GetAxis("Horizontal");
vertical = CrossPlatformInputManager.GetAxis("Vertical");
if (horizontal == 0 )
{
anim.SetBool("Idle", true);
Debug.Log("Idle");
}
else if(horizontal <=0 )// moving Player Back
{
anim.SetBool("Run", true);
anim.SetBool("Idle", false);
rb.transform.Translate(Vector3.back * speed * Time.deltaTime);
Debug.Log("Backward");
}
else if (horizontal >= 0)// moving player forward
{
anim.SetBool("Run", true);
anim.SetBool("Idle", false);
rb.transform.Translate(Vector3.forward * speed * Time.deltaTime);
Debug.Log("forward");
}
else if (vertical <=0)
{
anim.SetBool("Run", true);
anim.SetBool("Idle", false);
rb.transform.Translate(Vector3.left * speed * Time.deltaTime);
Debug.Log("left");
}
else if (vertical >= 0)
{
anim.SetBool("Run", true);
anim.SetBool("Idle", false);
rb.transform.Translate(Vector3.right * speed * Time.deltaTime);
Debug.Log("right");
}
}
// Update is called once per frame
void Update()
{
MoveHandler();
}
}
Answer by swanijam · Nov 07, 2018 at 02:37 PM
This could be because your animation is controlling the root transform/the transform the rigidbody is on. This can happen If the animator is on the same gameObject as the rigidbody or the transform you want to move through code.
Try toggling "Apply root motion" on the Animator component, or, place the animated player object inside a parent, and put the rigidbody on the parent. Move the parent instead of the animated player object.
Answer by AaronXRDev · Nov 07, 2018 at 02:37 PM
Your first check only looks at if horizontal is 0. Use both in that initial check.
if (horizontal == 0 && vertical ==0)