- Home /
Jumping while moving on the x axis being weird
When I move left or right and jump at the same time, my character jumps up half the height than it would if you stayed still, then it just floats down diagonally instead of falling. I want it to be like an arch jump, but its more of a right triangle. It looks like someone landing a parachute instead of jumping. Here's my code
public GameObject portal2;
public GameObject portal1;
private float portal2X;
private float portal2Y;
public float moveSpeed;
public float jumpForce;
private Rigidbody2D rb;
void Update()
{
portal2X = portal2.transform.position.x;
portal2Y = portal2.transform.position.y;
if(Input.GetKey(KeyCode.RightArrow))
{
rb.velocity = new Vector2(moveSpeed, 0f);
}
if (Input.GetKey(KeyCode.LeftArrow))
{
rb.velocity = new Vector2(-moveSpeed, 0f);
}
if(Input.GetKeyDown(KeyCode.Space))
{
rb.velocity = Vector2.up * jumpForce;
}
}
void Start()
{
rb = gameObject.GetComponent<Rigidbody2D>() as Rigidbody2D;
if(portal2.transform.rotation.z == 90)
{
portal2X = portal2X - 0.6f;
}
if(portal2.transform.rotation.z == 0)
{
portal2Y = portal2Y - 0.6f;
}
}
void OnCollisionEnter2D(Collision2D col)
{
if(col.gameObject == portal1)
{
transform.position = new Vector2(portal2X, portal2Y);
}
}
Answer by Andrew-Carvalho · Apr 18, 2019 at 08:54 PM
You overwrite your rigidbody's velocity every frame. This is fine when on the ground, but when you jump, if you are moving left or right you overwrite your velocity's y component with 0 every frame. Because of this, gravity can't correctly accelerate your character.
I would suggest calculating your horizontal and vertical speeds separately in local or member variables. Then, when you want to apply the new velocity to the rigidbody, you can add them together to get a proper final velocity.
Your answer
![](https://koobas.hobune.stream/wayback/20220612195734im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Why isn't my player looking the other direction when I wall jump (please help I am desperate) 1 Answer
How to fix the vibration while colliding and the suspension after jumping? 0 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Using isGrounded with a RigidBody 2 Answers