- Home /
2D Movement Mechanics for Platformer Game
I've been searching everywhere on the Internet, but I can't seem to find the right way of moving in 2D. There are so many different answers, some say to use transform (Translate and adding to position) and some say to use the Rigidbody for better physics (AddForce, velocity and MovePosition). But there are errors with everyone of these methods. For MovePosition, it slows down the character's falling speed. Most of them have errors with rotation too. I just have one question. What is the optimum way for moving in a simple 2d platfomer game? There are just too many answers out there and they confuse me. I hope someone can answer my question. I just want to be able to jump and move to the left and right.
My Current Code (Not Working):
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
Rigidbody2D rb;
public float movementSpeed = 15;
public float jumpForce;
float horizontalInput;
float verticalInput;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
}
private void Update()
{
horizontalInput = Input.GetAxis("Horizontal");
verticalInput = Input.GetAxis("Vertical");
}
private void FixedUpdate()
{
moveHorizontal(new Vector2(horizontalInput, -0.1f));
if (verticalInput > 0)
{
jump();
}
}
private void moveHorizontal (Vector2 direction)
{
rb.MovePosition(rb.position + (direction * movementSpeed * Time.fixedDeltaTime));
}
private void jump ()
{
rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
}
}
By errors with the rotation, I mean like the player falls down and stuff.