Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.

2D Movement Problem!

Discussion in 'Getting Started' started by EditoryArts, Dec 12, 2015.

  1. EditoryArts

    EditoryArts

    Joined:
    Jul 2, 2015
    Posts:
    1
    Hey i have created 2D movement with animations and all but for some reason when I turn left, it feels like there is a force that is slowing me down but when I go right I'm at the speed I want it to be.
    Any suggestions?

    Code:

    using UnityEngine;
    using System.Collections;

    public class player : MonoBehaviour
    {
    public float maxSpeed = 3;
    public float speed = 50f;
    public float jumpPower = 150f;

    public bool grounded;

    private Rigidbody2D rb2d;
    private Animator anim;

    void Start()
    {
    rb2d = gameObject.GetComponent<Rigidbody2D>();
    anim = gameObject.GetComponent<Animator>();
    }


    void Update()
    {


    anim.SetBool("Grounded" ,grounded);
    anim.SetFloat("Speed", Mathf.Abs(rb2d.velocity.x));

    if (Input.GetAxis("Horizontal") < -0.1f)
    {
    transform.localScale = new Vector3(-1, 1, 1);
    }

    if (Input.GetAxis("Horizontal") > 0.1f)
    {
    transform.localScale = new Vector3(1, 1, 1);
    }


    if(Input.GetButtonDown("Jump")&& grounded)
    {
    rb2d.AddForce(Vector2.up * jumpPower);
    }




    }

    void FixedUpdate()
    {

    Vector3 easeVelocity = rb2d.velocity;
    easeVelocity.y = rb2d.velocity.y;
    easeVelocity.z = 0.0f;
    easeVelocity.x *= 0.75f;


    float h = Input.GetAxis("Horizontal");

    //fake friction / Easing the x speed of our player
    if (grounded)
    {

    rb2d.velocity = easeVelocity;

    }


    //Moving the player
    rb2d.AddForce((Vector2.right * speed) * h);




    //limiting the speed of the player
    if (rb2d.velocity.x > maxSpeed)
    {
    rb2d.velocity = new Vector2(maxSpeed, rb2d.velocity.y);

    }

    if(rb2d.velocity.x < -maxSpeed)
    {
    rb2d.velocity = new Vector2(maxSpeed, rb2d.velocity.y);
    }

    }

    }
     
  2. Kurius

    Kurius

    Joined:
    Sep 29, 2013
    Posts:
    412
    I think in the last line of your code if current velocity is less than negative maxSpeed, then you should set the new velocity to Vector2(-maxSpeed, rb2d.velocity.y). Note the x value should be negative in this case.
     
  3. tedthebug

    tedthebug

    Joined:
    May 6, 2015
    Posts:
    2,570