Hello there!
I have a question that I have wondered about for a while now and found no solution to.
I’m using the code from Unity’s Live Training 16 Dec 2013 (2D Character Controller).
My character is controlled using the rigidbody2D’s velocity.
This has caused some problems
The first problem has to do with the jumping. The character sometimes jumps higher than what the jumpforce
is set to.
If you have watched the Live Training you know that there is a Physics2D.OverlapCircle
that checks if the character is grounded or not. From what I have deducted, the problem only occurs when the jump button is being spammed and the OverlapCircle
touches something whilst traveling upward.
A typical case would be if the character jumps up on an edge of a higher platform.
The character is then moving up at a velocity of jumpForce
, when hitting the edge (still traveling upwards and spamming the jump button), the OverlapCircle
detects ground and adds more jumpForce
which causes the character to travel upwards at a speed of jumpForce
+ rigidbody.velocity.y
.
I’ve tried to use the following code snippet I found (to limit the y
velocity):
if(rigidbody2D.velocity.y > 10f){
Vector2 clampedVel = rigidbody2D.velocity;
clampedVel.y = Mathf.Clamp(clampedVel.y, 0f, 10f);
rigidbody2D.velocity = clampedVel;
}
But it didn’t solve my problem
The second problem is similar to the jump problem, but concerns the movement instead.
My character is moved using the Input.getAxis()
method. When jumping and hugging a wall, the move
variable builds up from 0
to 1
(As you may know). The character can’t physically move but the move
variable is still building up, since the "Horizontal"
keys are being pressed. When the character then reaches the top of the wall, it moves super fast from one point to the other (since the move
variable has built up).
Movement code:
float move = Input.GetAxis ("Horizontal");
rigidbody2D.velocity = new Vector2(move * maxSpeed, rigidbody2D.velocity.y);
Jumping code:
rigidbody2D.AddForce(new Vector2(0,jumpForce));
TL;DR
My character is moving super fast sometimes when jumping and moving (see pic)
Q:
How would I go about to limit the traveling velocity so that said problems are not occurring?
Please take a look at the image below, I hope it can bring a bit more information to what I am trying to describe.
Thank you for your time and help!