2D Platformer smooth horizontal movement?
I'm very new to Unity and I'm trying to make a 2D platformer.
I'm currently using addforce for horizontal movement but I can't figure out a very minor problem. Hoping someone here could help me.
So with left and right movement, on the ground, its close to what I want where after moving say to the right for a while and the player gains some speed, if they switch to moving left they need to overcome a little momentum from when they were moving right before they start to move left. Kinda like how you would need a moment to skid to a halt.
My problem is, when the player is in the air, the same input this doesn't seem to be happening while the player is in the air (e.g when jumping) and I have no idea what I need to do to get it to act the same as it would if the player was on the ground.
Heres a quick visual of my problem (Sorry for the bad quality) where the top one is what I want when he turns (Starts going left then turns to go right) so theres a bit of resistance.
The bottom one is what I dont want, where he's just instantly moving at max speed the moment he turns around and this happens randomly when on the ground but all the time while in the air.
Heres my movement script which is in the Update() function:
//Horizontal Movement
Vector2 input = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
if (input.x != 0)
{
playerBody2D.AddForce(new Vector2(speed * input.x, 0));
//Speed capping
if (Mathf.Abs(playerBody2D.velocity.x) > maxSpeed)
{
playerBody2D.velocity = new Vector2(maxSpeed * input.x, playerBody2D.velocity.y);
}
}
//Flipping Sprite
if (Input.GetAxis("Horizontal") > 0)
{
transform.localScale = new Vector3(1f, 1f, 1f);
facingRight = true;
}
else if (Input.GetAxis("Horizontal") < 0)
{
transform.localScale = new Vector3(-1f, 1f, 1f);
facingRight = false;
}
I'm not great at coding so sorry if this is a simple noob problem and I'm just being dumb. I hope I've explained clearly.
Any help would be greatly appreciated, I'd been advised to use Physics and addforce which is what I've done here but if there are better ways of doing this, I would like to hear what suggestions people might have.
Answer by owen_unity55 · Dec 29, 2018 at 12:19 AM
In the first line of code try doing just Input.GetAxis
instead of Input.GetAxisRaw
. Not sure if it will work though, the part about it only working on the ground sometimes confuses me and I'm kind of new to Unity.
Good luck on the project and happy holidays!
Thanks for your reply. Unfortunately, it didn't change anything. I tested GetAxis and GetAxisRaw with my controller and $$anonymous$$eyboard, GetAxisRaw would always return 1/-1 as intended which is the reason I wanted to use it but while GetAxis will return a variety of values between 0-1 for $$anonymous$$eyboard and xbox360 controller, my other controller still returns 1/-1 regardless of which one I'm using.