Rigidbody very slow in air and weird bugs?

Updated on March 16, 2017 in [A] C# .Net
Share on Facebook0Tweet about this on Twitter0Share on Google+0Share on Reddit0
2 on March 14, 2017

Hey guys so I am working on a game and basically the player moves left and right completely fine but when the player jumps and I am holding left or right in air it goes down very slow, and sometimes I have weird bugs like for example I am holding left key down to move and space at same time I let go of arrow key and it flies high in the air.


public class PlayerMovement : MonoBehaviour {
public char defaultDirection;
public int playerMoveSpeed;

public int jumpSpeed;
private bool isPlayerGrounded;
public Rigidbody2D rb2D;

public Vector2 velocity;

void Start()

{

//is false because he starts game in the air

isPlayerGrounded = false;
rb2D = GetComponent<Rigidbody2D>();

}
void Update()

{

if(Input.GetKey(KeyCode.LeftArrow))

{

this.GetComponent<SpriteRenderer>().flipX = true;
//move player towards left

GetComponent<Rigidbody2D>().MovePosition(rb2D.position + -velocity * Time.deltaTime);

}
if (Input.GetKey(KeyCode.RightArrow))

{

this.GetComponent<SpriteRenderer>().flipX = false;
GetComponent<Rigidbody2D>().MovePosition(rb2D.position + velocity * Time.deltaTime);

}
}
void OnTriggerStay2D(Collider2D other)

{

if (other.GetComponent<Collider2D>().tag == "Floor")

if (Input.GetKeyDown(KeyCode.Space))

{

GetComponent<Rigidbody2D>().AddForce(new Vector3(0, 100, 0), ForceMode2D.Impulse);

}

}
}
  • Liked by
Reply
1 on March 14, 2017

You’re doing physics stuff in update.
Instead do it in fixedUpdate.

Wise
on March 16, 2017

Thanks that sorta worked I am using this code now:

This code works fine in update I don’t need fixed update?

using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour
{
    public float speed = 5f;
    public float jumpForce = 5f;
    private float movement = 0f;
    private Rigidbody2D rigidBody;
    public bool canJump;
    void Start()
    {
        jumpForce = 5000;
        rigidBody = GetComponent<Rigidbody2D>();
    }
    void Update()
    {
        movement = Input.GetAxis("Horizontal");
        if (movement > 0)
        {
            rigidBody.velocity = new Vector2(movement * speed, rigidBody.velocity.y);
            GetComponent<SpriteRenderer>().flipX = false;
        }
        else if (movement < 0f)
        {
            rigidBody.velocity = new Vector2(movement * speed, rigidBody.velocity.y);
            GetComponent<SpriteRenderer>().flipX = true;
        }
        else
        {
            rigidBody.velocity = new Vector2(0, rigidBody.velocity.y);
        }
        if (Input.GetKeyDown(KeyCode.Space) && rigidBody.GetComponent<Rigidbody2D>().velocity.y == 0)
        {
            rigidBody.AddForce(new Vector2(0, jumpForce));
        }
    }
}
Show more replies
  • Liked by
Reply
Cancel