└── PlayerController.cs /PlayerController.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | 3 | // Ensure the component is present on the gameobject the script is attached to 4 | // Uncomment this if you want to enforce the object to require the RB2D component to be already attached 5 | // [RequireComponent(typeof(Rigidbody2D))] 6 | public class PlayerController : MonoBehaviour 7 | { 8 | public Vector2 MovementSpeed = new Vector2(100.0f, 100.0f); // 2D Movement speed to have independant axis speed 9 | private new Rigidbody2D rigidbody2D; // Local rigidbody variable to hold a reference to the attached Rigidbody2D component 10 | private Vector2 inputVector = new Vector2(0.0f, 0.0f); 11 | 12 | void Awake() 13 | { 14 | // Setup Rigidbody for frictionless top down movement and dynamic collision 15 | // If RequireComponent is used uncomment the GetComponent and comment the AddComponent out 16 | // rigidbody2D = gameObject.GetComponent(); 17 | rigidbody2D = gameObject.AddComponent(); 18 | 19 | rigidbody2D.angularDrag = 0.0f; 20 | rigidbody2D.gravityScale = 0.0f; 21 | } 22 | 23 | void Update() 24 | { 25 | inputVector = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")).normalized; 26 | } 27 | 28 | void FixedUpdate() 29 | { 30 | // Rigidbody2D affects physics so any ops on it should happen in FixedUpdate 31 | // See why here: https://learn.unity.com/tutorial/update-and-fixedupdate# 32 | rigidbody2D.MovePosition(rigidbody2D.position + (inputVector * MovementSpeed * Time.fixedDeltaTime)); 33 | } 34 | } 35 | --------------------------------------------------------------------------------