Search Unity

Player Does not move

Discussion in '2D' started by sistemalberto19, Sep 21, 2017.

  1. sistemalberto19

    sistemalberto19

    Joined:
    Sep 21, 2017
    Posts:
    1
    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):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5.  
    6. public class PlayerManager : MonoBehaviour {
    7.  
    8.  
    9.     [SerializeField]
    10.     private float rigidSpeedX;
    11.  
    12.     public Animator anim;
    13.     public Rigidbody2D rd2d;
    14.     public SpriteRenderer sr;
    15.  
    16.     // Use this for initialization
    17.     void Start ()
    18.     {
    19.         sr = GetComponent<SpriteRenderer>();
    20.         anim = GetComponent<Animator>();
    21.         rd2d = GetComponent<Rigidbody2D>();
    22.  
    23.     }
    24.  
    25.     // Update is called once per frame
    26.     void Update ()
    27.     {
    28.         float moveHorizontal = Input.GetAxisRaw("Horizontal");
    29.         //playerSpeed += speedBoost;
    30.  
    31.         if (moveHorizontal != 0)
    32.         {
    33.             MoveHorizontal(moveHorizontal);
    34.         }
    35.         else
    36.         {
    37.             StopMoving();
    38.         }
    39.          
    40.     }
    41.     void MoveHorizontal(float moveHorizontal)
    42.     {
    43.  
    44.         if (moveHorizontal < 0)
    45.         {
    46.             sr.flipX = true;
    47.         }
    48.         else if (moveHorizontal > 0)
    49.         {
    50.             sr.flipX = false;
    51.         }
    52.  
    53.         this.transform.Translate(moveHorizontal * 10f, 0, 0);
    54.  
    55.         anim.SetInteger("State", 1);
    56.  
    57.         rigidSpeedX = this.GetComponent<Rigidbody2D>().velocity.x;
    58.         rd2d.GetComponent<Rigidbody2D>().velocity = new Vector2(moveHorizontal, rd2d.GetComponent<Rigidbody2D>().velocity.y);
    59.     }
    60.  
    61.     void StopMoving()
    62.     {
    63.         rd2d.velocity = new Vector2(0, rd2d.velocity.y);
    64.         anim.SetInteger("State", 0);
    65.  
    66.     }
     
  2. Deleted User

    Deleted User

    Guest

    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.