Search Unity

Help coding player movement

Discussion in '2D' started by Yunaaaa, Aug 7, 2019.

  1. Yunaaaa

    Yunaaaa

    Joined:
    May 11, 2019
    Posts:
    1
    Hi I've tried everything but my player doesn't move but the animations play (i mean that when i press the left arrow the left walking animation plays and the same for the other directions. The attack animation also plays when i press space). Please help
    This is my code:

    public enum PlayerState{
    walk,
    attack,
    idle
    }

    public class PlayerMovement : MonoBehaviour {


    public PlayerState currentState;
    public float speed;
    private Rigidbody2D myRigidbody;
    private Vector3 change;
    private Animator animator;


    // Use this for initialization
    void Start () {
    currentState = PlayerState.walk;
    animator = GetComponent<Animator>();
    myRigidbody = GetComponent<Rigidbody2D>();
    animator.SetFloat("moveX", 0);
    animator.SetFloat("moveY", -1);

    }

    // Update is called once per frame
    void Update () {
    change = Vector3.zero;
    change.x = Input.GetAxisRaw("Horizontal");
    change.y = Input.GetAxisRaw("Vertical");
    if(Input.GetButtonDown("attack") && currentState != PlayerState.attack)
    {
    StartCoroutine(AttackCo());
    }
    else if (currentState == PlayerState.walk || currentState == PlayerState.idle)
    {
    UpdateAnimationAndMove();
    }
    }

    private IEnumerator AttackCo()
    {
    animator.SetBool("attacking", true);
    currentState = PlayerState.attack;
    yield return null;
    animator.SetBool("attacking", false);
    yield return new WaitForSeconds(.3f);
    currentState = PlayerState.walk;
    }

    void UpdateAnimationAndMove()
    {
    if (change != Vector3.zero)
    {
    MoveCharacter();
    animator.SetFloat("moveX", change.x);
    animator.SetFloat("moveY", change.y);
    animator.SetBool("moving", true);
    }
    else
    {
    animator.SetBool("moving", false);
    }
    }

    void MoveCharacter()
    {
    change.Normalize();
    myRigidbody.MovePosition(
    transform.position + change * speed * Time.deltaTime
    );
    }
    }
     
  2. Cornysam

    Cornysam

    Joined:
    Feb 8, 2018
    Posts:
    1,465
    First off, please use code tags so it is much easier to understand your code. Second, I am not 100% sure but your "change" variable is being set to Vector3.zero every frame since it is in update. If you want to it to begin at 0, then put that line in start. But as i said, every single frame you are setting the "change" variable to Vector3.zero AND trying to grab the x and y from the horizontal and vertical inputs. Start with that and add some debug.logs to find out what is being called and what isnt. Or if everything is being called debug.log the values you are trying to change to see if those are behaving the way you want.
     
    buroks44 likes this.