Why is my character falling down slowly when I moving to right or left?

I have rigidbody issues. My character falling too slow when I moving to right or left. But if I don’t move anywhere It’s falling normally.

Here is the code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class movement : MonoBehaviour
{
//I changed script name. Original form is karakterhareket.
public Rigidbody2D rb;
public float speed, jumpforce;
public bool IsJump;

void Start()
{

}

void Update()
{
if(Input.GetKey(KeyCode.D))
{
rb.velocity = new Vector2(speed, 0);
}
if(Input.GetKey(KeyCode.A))
{
rb.velocity = new Vector2(-speed, 0);
}
if(IsJump==false)
{
if(Input.GetKeyDown(KeyCode.W)||Input.GetKeyDown(KeyCode.Space))
{
rb.velocity = new Vector2(0, jumpforce);
IsJump = true;
}
}
}

public void OnCollisionEnter2D(Collision2D other)
{
if(other.gameObject.name==“Square”)
{
IsJump = false;
}
}
}


8750511--1185564--upload_2023-1-23_16-23-32.png

Make sure the rotations which make it fall over are locked on the rigidbody. A rigidbody is just a physics object

1 Like

Assume that gravity accelerates you at 1 meter per second per frame, and that you move at 1 meter per second, to make the numbers nice.

First, if we are not moving

  • Frame 0: Velocity is (0,0)
  • Frame 1: Velocity is (0,-1)
  • Frame 2: Velocity is (0,-2)

This sounds reasonable. We go faster and faster as time goes on.

Now, what if we’re holding right?

  • Frame 0: Velocity is (1,0)
  • Frame 1: Velocity is (1,-1)
  • Frame 2: Velocity is (1,-1)

But why?

rb.velocity = new Vector2(speed, 0);

If you’re moving, your velocity’s x and y components are both set every frame. You keep resetting your vertical speed!

I would suggest reading your current velocity, setting just the x component, and writing it back to the rigidbody. This way, you aren’t constantly setting your y-velocity to zero every frame.

1 Like

Reply for DevDunk Thank you so much. 8750580--1185624--upload_2023-1-23_16-56-40.pngBut I already locked the Z rotation. I am working on 2D project. This i

Reply for chemicalcrux: Thank you but I didn’t understand. Can you tell shorly?

You’re doing this:

Vector2 velocity = new Vector2(1, 2);
velocity = new Vector2(3, 0);

The original y value is gone.

You want to do something more like this:

Vector2 velocity = new Vector2(1, 2);
velocity.x = 3;

One important thing: you can’t just do this*:

rb.velocity.x = 3;

So, you’ll need to do something like this instead:

Vector2 vel = rb.velocity;
vel.x = 3;
rb.velocity = vel;

Does that make sense?

*this happens because Vector2 is a value, like a float or an int. So, when you say rb.velocity, you wind up with a copy of its value; it’s not a reference to the original that you can modify.

1 Like

To chemicalcrux: I saw your reply after I started to fix the problem. Thank you for your all replies. But I did something different. I made what I understood. Thanks anyway.