Last active
February 22, 2021 16:11
-
-
Save silver-hornet/9ca8a2ca1e30a232b6d8a196a5cad24b to your computer and use it in GitHub Desktop.
2D Character Movement (with RigidBody2D)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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