Skip to content

Instantly share code, notes, and snippets.

@ryanapil
Last active March 31, 2020 11:07
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 ryanapil/b673c87e14d54d8a7064228ef01ae19b to your computer and use it in GitHub Desktop.
Save ryanapil/b673c87e14d54d8a7064228ef01ae19b to your computer and use it in GitHub Desktop.
Unity Input System FPS Movement

Unity Input System FPS Movement

C# player script utilizing Unity's latest Input System. WASD player movement and Mouse player view rotation.

Input Actions

  • Action Map Player
    • Action Movement (Pass Through, Vector 2)
      • Composite Primary (2D Vector, Digital Normalized)
        • Binding Up: W [Keyboard]
        • Binding Down: S [Keyboard]
        • Binding Left: A [Keyboard]
        • Binding Right: D [Keyboard]
    • Action View (Pass Through, Vector 2)
      • Binding Delta [Mouse]

Save Input Actions Asset. Enable Generate C# Class in the asset inspector then Apply.

Project

GameObject Player

  • Cube Model
  • Camera Player Camera

Attach Player.cs Script component to the GameObject and link the child Camera.

using UnityEngine;
using UnityEngine.InputSystem;
public class Player : MonoBehaviour {
InputActions controls;
public float speed = 1f;
public float sensitivity = 1f;
private Rigidbody rb;
public Camera playerCamera;
void Awake()
{
controls = new InputActions();
}
void Start()
{
rb = GetComponent<Rigidbody>();
Cursor.lockState = CursorLockMode.Locked;
}
void Update()
{
Movement(controls.Player.Movement.ReadValue<Vector2>());
View(controls.Player.View.ReadValue<Vector2>());
}
void Movement(Vector2 movement)
{
Vector3 horizontal = transform.right * movement.x;
Vector3 vertical = transform.forward * movement.y;
Vector3 velocity = (horizontal + vertical).normalized * speed;
if (velocity != Vector3.zero)
{
rb.MovePosition(rb.position + velocity * Time.deltaTime);
}
}
void View(Vector2 rotation)
{
Vector3 xRotation = new Vector3(-rotation.y, 0f, 0f) * sensitivity;
Vector3 yRotation = new Vector3(0f, rotation.x, 0f) * sensitivity;
rb.MoveRotation(rb.rotation * Quaternion.Euler(yRotation));
playerCamera.transform.Rotate(xRotation);
}
void OnEnable()
{
controls.Player.Enable();
}
void OnDisable()
{
controls.Player.Disable();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment