FiveArcher76571

Unity 101 - PlayerController.cs

Sep 16th, 2023
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.78 KB | Source Code | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class PlayerController : MonoBehaviour
  6. {
  7.     // The speed at which the player will move when going left and right
  8.     public float speed;
  9.  
  10.     // The amount of force that the player will jump with
  11.     public float jumpForce;
  12.  
  13.     // A reference to a Rigidbody2D component that's on our character
  14.     Rigidbody2D rb;
  15.  
  16.     // Start is called before the first frame update
  17.     void Start()
  18.     {
  19.         // Get the Rigidbody2D that's on our character
  20.         rb = GetComponent<Rigidbody2D>();
  21.     }
  22.  
  23.     // Update is called once per frame
  24.     void Update()
  25.     {
  26.         // If the player is pressing the A key
  27.         if(Input.GetKey(KeyCode.A))
  28.         {
  29.             // Time.deltaTime is the time between this frame and the last frame
  30.             // We use this whenever moving because we want to keep the speed constant
  31.             // Even if our frame rate drops
  32.             Vector2 delta = new Vector2(-speed * Time.deltaTime, 0);
  33.  
  34.             // The transform.Translate function moves our GameObject directly by a certain amount
  35.             transform.Translate(delta);
  36.         }
  37.         // If the player is pressing the D key
  38.         else if (Input.GetKey(KeyCode.D))
  39.         {
  40.             // Same thing as above, except we don't negate the speed
  41.             Vector2 delta = new Vector3(speed * Time.deltaTime, 0);
  42.             transform.Translate(delta);
  43.         }
  44.  
  45.         // Input.GetKeyDown checks for weather the space key was pressed this frame
  46.         if(Input.GetKeyDown(KeyCode.Space))
  47.         {
  48.             Vector2 forceToAdd = new Vector2(0, jumpForce);
  49.  
  50.             // AddForce adds an actual force to the object
  51.             rb.AddForce(forceToAdd);
  52.         }
  53.     }
  54. }
  55.  
Advertisement
Add Comment
Please, Sign In to add comment