Search Unity

Help me fix this problem -noob here-

Discussion in '2D' started by nrlhq, Mar 22, 2017.

  1. nrlhq

    nrlhq

    Joined:
    Mar 22, 2017
    Posts:
    2
    Hey there, I am new ti unity and trying to get familiar with it and its API I've created a character and wrote script to make it move and jump, everything works fine but when the character jumps and I press 'A' or 'D' to make it move on x-axis it starts moving in that direction gets back to ground very slowly

    here's the video that shows the problem i am having
    https://s3.amazonaws.com/img0.recor...193888&Signature=y4LNuKYxskKCnOxvaA4QSqqzP9U=

    and here's the script

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class Player : MonoBehaviour {
    public float speed;
    public float jumpSpeed;
    private Rigidbody2D rb;
    private Animator animator;

    void Start () {
    rb = GetComponent<Rigidbody2D> ();
    animator = GetComponent<Animator> ();
    }

    void FixedUpdate () {
    float movementHorizontal = Input.GetAxis ("Horizontal");

    animator.SetBool ("Run", false);
    if (movementHorizontal > 0 || movementHorizontal < 0) {
    if(movementHorizontal < 0)
    transform.rotation = Quaternion.Euler(new Vector2(0, 180));
    else
    transform.rotation = Quaternion.Euler(new Vector2(0, 0));

    rb.velocity = new Vector2 (speed * movementHorizontal, 0.0f);
    animator.SetBool ("Run", true);

    }

    if ( Input.GetKeyDown ("w") ) {
    animator.SetBool ("Run", false);
    rb.AddForce (new Vector2 (0, jumpSpeed), ForceMode2D.Impulse);
    }

    }
    }
     
  2. DanielQuick

    DanielQuick

    Joined:
    Dec 31, 2010
    Posts:
    3,137
    Please use code tags when posting code.

    You are setting the velocity directly when pressing A/D, manually setting the vertical velocity to 0.
    Either use forces, like you are for W, or set the vertical velocity to the existing vertical velocity when pressing A/D.
     
  3. nrlhq

    nrlhq

    Joined:
    Mar 22, 2017
    Posts:
    2
    Thanks Daniel i changed this

    rb.velocity = new Vector2 (speed * movementHorizontal, 0.0);
    to
    rb.velocity = new Vector2 (speed * movementHorizontal, rb.velocity.y);

    and works perfectly now. :)