Edwarddv

SimpleWASDMovement

Mar 28th, 2021
877
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.22 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class SimpleWASDMovement : MonoBehaviour
  6. {
  7.  
  8.     public Rigidbody thisRigidbody;
  9.     public Camera thisCamera;
  10.     public float speed = 1f;
  11.     public float jumpStrength = 1f;
  12.  
  13.  
  14.     // Start is called before the first frame update
  15.     void Start()
  16.     {
  17.         if (!thisRigidbody)
  18.             thisRigidbody = GetComponent<Rigidbody>();
  19.         if (!thisCamera)
  20.             thisCamera = Camera.main;
  21.     }
  22.  
  23.     // Update is called once per frame
  24.     void Update()
  25.     {
  26.         MovementInput();
  27.         LookInput();
  28.     }
  29.  
  30.     void MovementInput()
  31.     {
  32.         Vector3 movementVector = Vector3.zero;
  33.         movementVector.z -= Input.GetAxis("Horizontal");
  34.         movementVector.x += Input.GetAxis("Vertical");
  35.  
  36.  
  37.         if (Input.GetButtonDown("Jump"))
  38.         {
  39.             if (Physics.Raycast(transform.position, -Vector3.up, 1f))
  40.             {
  41.                 thisRigidbody.AddForce(Vector3.up * jumpStrength, ForceMode.Impulse);
  42.  
  43.             }
  44.         }
  45.  
  46.  
  47.         if (thisCamera) // adjust the movement vector to be relative to the camera
  48.         {
  49.             Vector3 adjustVector = -thisCamera.transform.right;
  50.             adjustVector.y = 0;
  51.             movementVector = Quaternion.LookRotation(adjustVector.normalized, Vector3.up) * movementVector;
  52.         }
  53.  
  54.         thisRigidbody.MovePosition(transform.position + movementVector * speed);
  55.     }
  56.  
  57.  
  58.     public Transform cameraPivot;
  59.     public float cameraSpeed = 1f;
  60.     public bool invertVertical = false;
  61.     public float maxVertical = 60f;
  62.     public float minVertical = 10f;
  63.     void LookInput()
  64.     {
  65.         float camHorizontal = Input.GetAxis("Mouse X") * cameraSpeed;
  66.         float camVertical = -Input.GetAxis("Mouse Y") * cameraSpeed;
  67.         if (invertVertical)
  68.             camVertical *= -1f;
  69.  
  70.         Vector3 newRotation = new Vector3(cameraPivot.transform.localRotation.eulerAngles.x + camVertical, cameraPivot.transform.localRotation.eulerAngles.y + camHorizontal, 0f);
  71.         newRotation.x = Mathf.Clamp(newRotation.x, minVertical, maxVertical);
  72.         cameraPivot.transform.localRotation = Quaternion.Euler(newRotation);
  73.  
  74.     }
  75.  
  76. }
  77.  
Advertisement
Add Comment
Please, Sign In to add comment