Player loses momentum when landing
Hey! C# and Unity amateur here, happy to post my first question on the forum.
I'm making a small 2D sidescroller game and I have an issue with my player movement. After a lot of tinkering, everything seems to work well other than one thing: When the player lands after a jump, they lose their momentum instead of keeping it.
How can I preserve the player's momentum after they land, so that they immediately continue moving forward if they hold the directional key?
Here's my code. Thanks for your help! using UnityEngine; using System.Collections;
public class playerController : MonoBehaviour {
public Rigidbody2D player;
public GameObject playerObj;
public Animator playerAnim;
//For collision checking
public BoxCollider2D floorColl;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
//Move right
if (Input.GetKey("right") && !InAirChecker())
{
gameObject.transform.localScale = new Vector3(1, 1, 1);
playerAnim.Play("Run");
if (player.velocity.magnitude < 2.5f)
{
player.AddForce(new Vector2(15, 0), ForceMode2D.Force);
}
}
if (Input.GetKeyUp("right") && !InAirChecker())
{
playerAnim.Play("Idle");
player.velocity = new Vector2(0f, 0f);
}
//Move left
if (Input.GetKey("left") && !InAirChecker())
{
gameObject.transform.localScale = new Vector3(-1, 1, 1);
playerAnim.Play("Run");
if (player.velocity.magnitude < 2.5f)
{
player.AddForce(new Vector2(-15, 0), ForceMode2D.Force);
}
}
if (Input.GetKeyUp("left") && !InAirChecker())
{
playerAnim.Play("Idle");
player.velocity = new Vector2(0f, 0f);
}
//Jump!
if (Input.GetKeyDown("up") && !InAirChecker())
{
player.AddForce(new Vector2(0, 5), ForceMode2D.Impulse);
playerAnim.Play("Jump");
}
}
bool InAirChecker()
{
bool inAir;
if (player.IsTouchingLayers())
{
inAir = false;
}
else
{
inAir = true;
}
return inAir;
}
}
Your answer
Follow this Question
Related Questions
Player Movement Not Always Responding 1 Answer
How to move the player only 1 tile per buttonPress? 2 Answers
Problem with a multi-jump script ( C# ) 1 Answer
Player not moving in the right direction instantly 1 Answer
Unity 2D jump "fly" 0 Answers