Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class PlayerController : MonoBehaviour
- {
- // The speed at which the player will move when going left and right
- public float speed;
- // The amount of force that the player will jump with
- public float jumpForce;
- // A reference to a Rigidbody2D component that's on our character
- Rigidbody2D rb;
- // Start is called before the first frame update
- void Start()
- {
- // Get the Rigidbody2D that's on our character
- rb = GetComponent<Rigidbody2D>();
- }
- // Update is called once per frame
- void Update()
- {
- // If the player is pressing the A key
- if(Input.GetKey(KeyCode.A))
- {
- // Time.deltaTime is the time between this frame and the last frame
- // We use this whenever moving because we want to keep the speed constant
- // Even if our frame rate drops
- Vector2 delta = new Vector2(-speed * Time.deltaTime, 0);
- // The transform.Translate function moves our GameObject directly by a certain amount
- transform.Translate(delta);
- }
- // If the player is pressing the D key
- else if (Input.GetKey(KeyCode.D))
- {
- // Same thing as above, except we don't negate the speed
- Vector2 delta = new Vector3(speed * Time.deltaTime, 0);
- transform.Translate(delta);
- }
- // Input.GetKeyDown checks for weather the space key was pressed this frame
- if(Input.GetKeyDown(KeyCode.Space))
- {
- Vector2 forceToAdd = new Vector2(0, jumpForce);
- // AddForce adds an actual force to the object
- rb.AddForce(forceToAdd);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment