# jumping and movement with rigidbody2d.velocity, gravity problem

i'm making a 2d platformer and i move my character with rigidbody2d.velocity swiping up to jump and moving while holding the left or right side of the screen.

the problem is that when i jump and i try to move left or right in the air, my character falls very slowly. i've read that the reason why that happens is because rb.velocity overrides gravity at every frame, is there a way to move left or right in the air with normal gravity?

my full code is

{
Rigidbody2D rb;
public float speed = 1f;
public float jumpforce = 3.5f;
private Vector3 mouseDownPos;
private float startTime = 0f;
public float holdTime = 0.15f;

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

void Update()
{

if (Input.GetMouseButtonDown(0))
{

mouseDownPos = Input.mousePosition;
startTime = Time.time;
}

if (Input.GetMouseButtonUp(0))
{

if ( startTime + holdTime > Time.time & Input.mousePosition == mouseDownPos)// tap
{ Debug.Log("T A P");}

if (Input.mousePosition.y > mouseDownPos.y + 100 )//jump
{

rb.velocity = new Vector2(rb.velocity.x, jumpforce);
}

}

if (Input.GetMouseButton(0) & startTime + holdTime <= Time.time)///move while grounded
{
if (Input.mousePosition.x < Screen.width / 2)
{
Debug.Log("Left click");
rb.velocity = transform.right * speed;

}
else if (Input.mousePosition.x > Screen.width / 2)
{
Debug.Log("Right click");
rb.velocity = transform.right * speed;

}

if (Input.mousePosition.x < Screen.width / 2)/// move while in the air
{
Debug.Log("Left click");

rb.velocity = new Vector2(-speed, rb.velocity.y);

}
else if (Input.mousePosition.x > Screen.width / 2)
{
Debug.Log("Right click");

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

}

}

}


the rigidbody2d of my character is

I've read that the reason why that happens is because rb.velocity overrides gravity at every frame, is there a way to move left or right in the air with normal gravity?

Did you try something simple like preserving the current vertical velocity, and overriding only the part you want to change?

// Cache the current velocity to modify it.
Vector3 newVelocity = rb.velocity;

// For left/right input, modify only the x part of the velocity.
if (Input.mousePosition.x < Screen.width / 2)
{
newVelocity.x = speed;
}
else if (Input.mousePosition.x > Screen.width / 2)
{
newVelocity.x = -speed;
}

// Apply the modified velocity to our body.
// (If no modification happened, then this just preserves the existing velocity)
rb.velocity = newVelocity;

• yeah, i tried that and it still goes down very slowly Apr 7 '19 at 23:48
• Show us exactly what you did. The code you've shown still overrides vertical velocity in several places. Apr 7 '19 at 23:51