Skip to content

Instantly share code, notes, and snippets.

@GT3000
Created April 7, 2021 06:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GT3000/5533336f660e2c4a204bad655115171a to your computer and use it in GitHub Desktop.
Save GT3000/5533336f660e2c4a204bad655115171a to your computer and use it in GitHub Desktop.
Real Simple 2D Movement
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
[SerializeField] private float speed; //Controls player speed, this can be adjusted
private Vector3 playerPos; //Sets player position
// Start is called before the first frame update
void Start()
{
playerPos = Vector3.zero; //Sets PlayerPos to zero in the world space
transform.position = playerPos; //Sets the Player's transform to PlayerPos
}
// Update is called once per frame
void Update()
{
//As players move either WASD or the arrow keys (or whatever keys are defined by Unity's input system) every frame, playerPos is updated
playerPos = new Vector3(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"));
//Uses transform.Translate to communicate to Player GameObject to move where PlayerPos is
//Time.delta simply translate this movement into real-time seconds instead of frames
//The speed variable dictates how fast the Player moves over time
transform.Translate(playerPos * Time.deltaTime * speed);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment