I have a character in a 2D platformer that is running at a fixed pace. When the character runs into a wall and stops, his velocity remains 5. This makes it impossible for me to set an idle animation since the velocity doesn’t change although the character is no longer moving. I made a new project and distilled it down to the fundamentals to display the issue, you can see it here.
If I assign a keypress to the move speed, it works properly. As soon as the character hits the wall, his velocity becomes 0, even if you continue holding the key.
You can see that here.
The player is not supposed to have control of the character’s movement. So how do I have the character move at a fixed velocity, but have his velocity go to zero once he hits a wall? If there is some workaround to identify that he has hit a wall even with a velocity value, that would work too, I have just been unable to figure one out.
Hi,
I think it has something to do with the way that your are using velocity. You seem to be trying to use it to set the velocity. The keyword Velocity should be used to read the current velocity of the object. Below is my code from a basic 2D game. Hopefully you’ll be able to pick bits out of it to help you:
void FixedUpdate()
{
float h = Input.GetAxis("Horizontal");
anim.SetFloat("speed", Mathf.Abs(rb2d.velocity.x));
if (h * rb2d.velocity.x < maxSpeed)
rb2d.AddForce(Vector2.right * h * moveForce);
if (Mathf.Abs (rb2d.velocity.x) > maxSpeed)
rb2d.velocity = new Vector2(Mathf.Sign (rb2d.velocity.x) * maxSpeed, rb2d.velocity.y);
Debug.Log (rb2d.velocity);
if (h > 0 && !facingRight)
Flip ();
else if (h < 0 && facingRight)
Flip ();
if (jumping)
{
anim.SetTrigger ("jump");
anim.SetBool ("land", false);
rb2d.AddForce(new Vector2(0f, jumpForce));
jumping = false;
}
if (rb2d.velocity.y < 0)
{
anim.SetBool ("land", true);
}
if (rb2d.velocity.y == 0) {
anim.SetBool ("land", false);
}
HandleLayers ();
}