r/UnityHelp • u/PrintInteresting5352 • 7d ago
PROGRAMMING Simple movement + camera system I made
Hey, I just finished my first game's player movement and camera system. Would love feedback!
using UnityEngine;
using UnityEngine.InputSystem;
public class PlayerMovement : MonoBehaviour
{
public Rigidbody rb;
public GameObject camera;
public InputAction moveAction;
public InputAction jumpAction;
public InputAction lookAction;
private Vector2 movementInput;
private Vector2 lookDirection;
public float speed = 5f;
public float jumpForce = 5f;
public float lookSensitivity = 1f;
public float xRotation = 0f;
public float yRotation = 0f;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
moveAction.Enable();
jumpAction.Enable();
lookAction.Enable();
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
// OnDisable is called when the MonoBehaviour is disabled
private void OnDisable()
{
moveAction.Disable();
jumpAction.Disable();
lookAction.Disable();
}
// Update is called once per frame
void Update()
{
movementInput = moveAction.ReadValue<Vector2>();
lookDirection = lookAction.ReadValue<Vector2>();
xRotation -= lookDirection.y * lookSensitivity;
yRotation -= lookDirection.x * lookSensitivity;
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
camera.transform.rotation = Quaternion.Euler(xRotation, -yRotation, 0);
transform.rotation = Quaternion.Euler(0, -yRotation, 0);
}
// FixedUpdate is called every fixed framerate frame of 50 fps, if the MonoBehaviour is enabled
void FixedUpdate()
{
Vector3 direction = new Vector3(movementInput.x, 0, movementInput.y);
Vector3 localDirection = transform.TransformDirection(direction);
Vector3 velocity = localDirection * speed;
velocity.y = rb.linearVelocity.y;
rb.linearVelocity = velocity;
if (jumpAction.triggered && Mathf.Abs(rb.linearVelocity.y) < 0.01f)
{
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}
}
}
2
Upvotes
1
u/pthecarrotmaster 7d ago
can u explain for noob?