The question is answered, right answer was accepted
How to keep upward momentum after reversing gravity
I am currently working on a small 2D game with a gravity shifting mechanic and I have come acros a small problem which I hope someone could be able to help me with.
The concept is rather simple, I have an object moving along the X axis and it has two functions - a Jump and a Shift. Jump is simple enough, and as for Shift, what it does is changes the players Y position to the oposite and reverses the gravity - up is down and down is up.
The problem comes with jumping and shifting at the same time, as I shift while jumping the object reverses the gravity and looses all of its upward momentum and plumets down/up.
What I would like to achieve is the ability to keep the upward/downward momentum after a shift.
Here is the code I have writen thus far for both of the functions:
public void Jump()
{
if ((isGrounded && rb.velocity.y <= 0 && rb.velocity.y >= 0))
{
jumpsAvailable = 1;
}
if (jumpsAvailable > 0)
{
canJump = true;
}
else
{
canJump = false;
}
if (Input.GetKeyDown(KeyCode.UpArrow) && canJump && isUp)
{
rb.velocity = Vector2.up * jumpForce;
jumpsAvailable--;
}
else if (Input.GetKeyDown(KeyCode.UpArrow) && canJump && !isUp)
{
rb.velocity = Vector2.down * jumpForce;
jumpsAvailable--;
}
}
public void Shift()
{
if (Input.GetKeyDown(KeyCode.Space) && isUp)
{
if (!isGrounded)
{
transform.position = transform.position + new Vector3(0,
(-transform.position.y * 2)
+ (-transform.localScale.y + 0.074294f), 0);
rb.gravityScale = -3;
isUp = !isUp;
}
else
{
transform.position = transform.position
+ (new Vector3(0, -transform.localScale.y + 0.074294f, 0));
rb.gravityScale = -3;
isUp = !isUp;
}
}
else if (Input.GetKeyDown(KeyCode.Space) && !isUp)
{
if (!isGrounded)
{
transform.position = transform.position + (new Vector3(0,
(-transform.position.y * 2)
- transform.localScale.y - 0.03899369f, 0));
rb.gravityScale = 3;
isUp = true;
}
else
{
transform.position = transform.position +
(new Vector3(0, transform.localScale.y - 0.03899369f, 0));
rb.gravityScale = 3;
isUp = true;
}
}
}
Curently the only solution I was able to think of was to delay the gravity shift while there is still upward/downward momentum, but I am not certain that it would be the optimal solution, so I thought that it would be better to try and get an answer here.
Was able to solve this by changing the Y velocity right after the gravity change rb.velocity = new Vector2(rb.velocity.x, -rb.velocity.y)
Follow this Question
Related Questions
Player loses momentum when landing 0 Answers
Ground check doesnt work 0 Answers
Jumping with rigid body velocity doesn't feel good 1 Answer
Problem with a multi-jump script ( C# ) 1 Answer
2D Platform irregular jump 1 Answer