Hello everyone I am trying to move my player left to right but it does not move. Could you all please check my code Thank you Code (CSharp): using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerManager : MonoBehaviour { [SerializeField] private float rigidSpeedX; public Animator anim; public Rigidbody2D rd2d; public SpriteRenderer sr; // Use this for initialization void Start () { sr = GetComponent<SpriteRenderer>(); anim = GetComponent<Animator>(); rd2d = GetComponent<Rigidbody2D>(); } // Update is called once per frame void Update () { float moveHorizontal = Input.GetAxisRaw("Horizontal"); //playerSpeed += speedBoost; if (moveHorizontal != 0) { MoveHorizontal(moveHorizontal); } else { StopMoving(); } } void MoveHorizontal(float moveHorizontal) { if (moveHorizontal < 0) { sr.flipX = true; } else if (moveHorizontal > 0) { sr.flipX = false; } this.transform.Translate(moveHorizontal * 10f, 0, 0); anim.SetInteger("State", 1); rigidSpeedX = this.GetComponent<Rigidbody2D>().velocity.x; rd2d.GetComponent<Rigidbody2D>().velocity = new Vector2(moveHorizontal, rd2d.GetComponent<Rigidbody2D>().velocity.y); } void StopMoving() { rd2d.velocity = new Vector2(0, rd2d.velocity.y); anim.SetInteger("State", 0); }
You should first decide how you want your player to move, you're using transform.translate and setting the velocity of the rigidbody, you don't want to do both. You are also being redundant with your get components, once you've set them in your start function you don't need to call getcomponent again. Try removing the transform.translate and see if it behaves the way you'd like it to.