Skip to content

Instantly share code, notes, and snippets.

@silver-hornet
Last active February 22, 2021 16:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save silver-hornet/9ca8a2ca1e30a232b6d8a196a5cad24b to your computer and use it in GitHub Desktop.
Save silver-hornet/9ca8a2ca1e30a232b6d8a196a5cad24b to your computer and use it in GitHub Desktop.
2D Character Movement (with RigidBody2D)
// This script enables simple, horizontal 2D character movement with a RigidBody2D.
// Ensure you have added a RigidBody2D component in the Inspector and have set its Body Type to Dynamic.
// GetAxisRaw makes the movement snappy, so the player instantly stops. If you want smoother movement, use GetAxis instead.
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
[SerializeField] float speed = 4f;
Rigidbody2D rb;
float movement;
void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
movement = Input.GetAxisRaw("Horizontal") * speed; //GetAxis is smoother; GetAxisRaw is snappier
}
void FixedUpdate()
{
rb.MovePosition(rb.position + new Vector2(movement * Time.deltaTime, 0f));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment