2D Player Movement In Unity

2 min read 4 months ago
Published on Apr 22, 2024 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

How to Create 2D Player Movement in Unity

Step 1: Setting Up the Scene

  1. Create a new Unity project and set up a small demo scene with platforms.
  2. Add a Sprite Renderer and a Box Collider 2D to each platform.
  3. Import sprites for platforms, player, and reset their position, rotation, and scale.

Step 2: Setting Up the Player

  1. Add a Sprite Renderer to the player and select a player sprite.
  2. Add a Rigid Body 2D and a Box Collider 2D to the player.
  3. Increase the gravity scale for the player.
  4. Set collision detection to continuous, sleeping mode to never sleep, and interpolation to interpolate be affected by physics.
  5. Create a child object called "groundcheck" and position it at the player's feet.

Step 3: Writing the Player Movement Script

  1. Create a new C# script for player movement.
  2. Define private variables for horizontal input, speed, jumping power, and a boolean for player facing direction.
  3. Add serialized fields to reference the rigid body, ground check, and ground layer.
  4. In the Update method, get horizontal input using Input.GetAxisRaw("Horizontal").
  5. In the FixedUpdate method, set the player's horizontal movement based on input and speed.
  6. Implement player flipping based on the direction of movement.
  7. Implement jumping by checking if the player is grounded using Physics2D.OverlapCircle.
  8. Allow the player to jump higher by holding the jump button longer.

Step 4: Organizing and Finalizing

  1. Move the script to a "Scripts" folder for organization.
  2. Create a new layer called "Ground" and assign it to every platform.
  3. Set the friction and bounciness of the ground to 0 and drag it onto the player.
  4. Reference the rigid body, ground check, and ground layer in the player movement script.

Step 5: Testing and Refinement

  1. Hit play to test the player movement and jumping functionality.
  2. Ensure the player can move and jump smoothly without issues.
  3. Make adjustments to the script or scene as needed for better gameplay experience.

By following these steps, you can create a basic 2D player movement system in Unity similar to the one demonstrated in the tutorial video by bendux. Feel free to customize and expand upon this foundation to suit your game development needs.