Velocity Issue while Switching Gravity

Hello everyone,

I’m currently making a 2D platformer game without jumping, where gravity (for the player only) can be switched in up, down, left and right direction. The overall gravity of the physics engine is set to 0.

Here is what it looks like :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GravityPlatformer : MonoBehaviour
{
public int GravityDirection = 270; //0=right 90=up 180=left 2 70=down
public float maxFallingSpeed = 10f;
public float gravityForceAmount = -1000f;

private Rigidbody2D rb2d;
private ConstantForce2D customGravity;

void Awake()
{
rb2d = GetComponent();
customGravity = GetComponent();
customGravity.force = new Vector2(0, gravityForceAmount);
}

void Update()
{
}

void FixedUpdate()
{
if (GravityDirection == 90 | GravityDirection == 270)
{
if (Mathf.Abs(rb2d.velocity.y) > maxFallingSpeed)
rb2d.velocity = new Vector2(rb2d.velocity.x, Mathf.Sign(rb2d.velocity.y) * maxFallingSpeed);
}

if (GravityDirection == 0 | GravityDirection == 180)
{
if (Mathf.Abs(rb2d.velocity.x) > maxFallingSpeed)
rb2d.velocity = new Vector2(Mathf.Sign(rb2d.velocity.x) * maxFallingSpeed, rb2d.velocity.y);
}

if (GravityDirection != 270 && Input.GetButtonDown(“downGravity”))
{
rb2d.velocity = new Vector2(0, 0);
customGravity.force = new Vector2(0, gravityForceAmount);
GravityDirection = 270;
}

if (GravityDirection != 0 && Input.GetButtonDown(“rightGravity”))
{
rb2d.velocity = new Vector2(0, 0);
customGravity.force = new Vector2(-gravityForceAmount, 0);
GravityDirection = 0;
}

if (GravityDirection != 90 && Input.GetButtonDown(“upGravity”))
{
rb2d.velocity = new Vector2(0, 0);
customGravity.force = new Vector2(0, -gravityForceAmount);
GravityDirection = 90;
}

if (GravityDirection != 180 && Input.GetButtonDown(“leftGravity”))
{
rb2d.velocity = new Vector2(0, 0);
customGravity.force = new Vector2(gravityForceAmount, 0);
GravityDirection = 180;
}

What I want is to have the velocity stop completely when I change gravity to make platofrming more precise. But during the test I have this problem.

When I press UpGravity the velocity becomes (0,10) (as it should) but when I press leftGravity the velocity becomes (-10,2) instead of (-10,0) as desired. This happens in every direction changes, the object adds 10 velocity in the new direction but keeps 2 velocity in its previous direction.

Does anyone have any idea how to fix that ? Thanks by advance for your answers.

I’ve found a solution, in the “RigidBody2D” box of the object, I increased Linear Drag to 10 and now it makes perfect right angles. I don’t know how to mark this thread as “answered”, can a moderator please do it ?