- Home /
How do I stop the player from gliding while in the air?
The movement code seems to conflict with each other. The character can't jump while moving left or right. Once it does jump, the player can simply glide back and forth. How do I fix these issues?
A video I took:
My code:
public float moveSpeed;
public float jumpForce;
private Rigidbody2D rb;
//health
public float playerHealth;
// Use this for initialization
void Start () {
rb = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update () {
//movement
if (Input.GetKeyDown(KeyCode.W))
{
rb.velocity = new Vector2(0, jumpForce);
}
if (Input.GetKey(KeyCode.A))
{
rb.velocity = new Vector2(-moveSpeed, 0);
}
if (Input.GetKey(KeyCode.D))
{
rb.velocity = new Vector2(moveSpeed, 0);
}
Answer by Atiyeh123 · Sep 16, 2018 at 05:43 PM
Hi, the inputs doesn't conflict with each other.there is a mistake in your code. if you want to jump while moving if you set x velocity to 0 it doesn't move anymore . change these lines:
//movement
if (Input.GetKeyDown(KeyCode.W))
{
rb.velocity = rb.velocity + Vector2.up*jumpForce;
}
if (Input.GetKey(KeyCode.A))
{
rb.velocity = rb.velocity - Vector2.right*moveSpeed;
}
if (Input.GetKey(KeyCode.D))
{
rb.velocity = rb.velocity + Vector2.right*moveSpeed;
}
It does fix the problem but it created another one. I don't want the player to build up speed. I want it to be constant.
I fixed it myself with this new code: In the place of the zeros, I put rb.velocity.y or x.
Your answer
Follow this Question
Related Questions
Making a bubble level (not a game but work tool) 1 Answer
Distribute terrain in zones 3 Answers
How to fix wobbling float when away from spawn? 1 Answer
Smoothly move 2D Sprite 2 Answers
2D Character Movement 1 Answer