PBG2H23ABR_PBG2H23AKL_PMC_P.../Plunderblock/Assets/Scripts/ScriptsJan/PlayerScripts/PlayerMoveScript.cs

123 lines
3.4 KiB
C#

using System.Collections;
using System.Collections.Generic;
using System.Threading;
using Unity.VisualScripting;
using UnityEngine;
public class PlayerMoveScript : MonoBehaviour
{
[Header("Movement")]
[SerializeField] private float speed;
[SerializeField] private float jumpForce;
[SerializeField] private float jumpPointDistance;
[SerializeField] private float jumpPointRadius;
[Header("Looking")]
[SerializeField] private float xSensitivity;
[SerializeField] private float ySensitivity;
[SerializeField] private Camera cam;
private Rigidbody rb;
private bool cursorIsLocked;
private LayerMask ground;
void Start()
{
rb = GetComponent<Rigidbody>();
Cursor.lockState = CursorLockMode.Locked;
cursorIsLocked = true;
ground = LayerMask.GetMask("Ground");
}
// Update is called once per frame
void Update()
{
jump();
move();
look();
lockCursor();
}
public void move()
{
// In welche Richtung rennt der Spieler?
int moveDirX = 0;;
int moveDirZ = 0;
if(Input.GetKey(KeyCode.W)){moveDirZ++;}
if(Input.GetKey(KeyCode.S)){moveDirZ--;}
if(Input.GetKey(KeyCode.D)){moveDirX++;}
if(Input.GetKey(KeyCode.A)){moveDirX--;}
Vector3 moveDir = new Vector3(moveDirX, 0, moveDirZ);
moveDir.Normalize();
rb.velocity = transform.TransformDirection(new Vector3(moveDir.x * speed, rb.velocity.y, moveDir.z * speed));
}
public void jump()
{
if(Input.GetKey(KeyCode.Space))
{
if (Physics.CheckSphere(transform.position + Vector3.down * jumpPointDistance, jumpPointRadius, ground) )
{
rb.isKinematic = true;
rb.isKinematic = false;
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}
}
}
void OnDrawGizmosSelected()
{
// Draws a Line for checkForJump
Gizmos.color = Color.red;
Vector3 direction = transform.TransformDirection(Vector3.down) * jumpPointDistance;
Gizmos.DrawRay(transform.position, direction);
// Draw a yellow sphere at the transform's position
Gizmos.color = Color.blue;
Gizmos.DrawWireSphere(transform.position + Vector3.down * jumpPointDistance, jumpPointRadius);
}
public float newDirY;
public void look()
{
float xMouseMovement = Input.GetAxis("Mouse X") * xSensitivity * Time.deltaTime;
float yMouseMovement = Input.GetAxis("Mouse Y") * ySensitivity * Time.deltaTime;
Vector3 currentRotation = cam.transform.rotation.eulerAngles;
float newDirX = currentRotation.y + xMouseMovement;
newDirY = newDirY - yMouseMovement;
newDirY = Mathf.Clamp(newDirY, -90f, 90f);
cam.transform.localRotation = Quaternion.Euler(newDirY, 0, 0);
transform.localRotation = Quaternion.Euler(0, newDirX, 0);
}
public void lockCursor()
{
if (Input.GetKeyDown(KeyCode.Escape))
{
if(!cursorIsLocked)
{
Cursor.lockState = CursorLockMode.Locked;
cursorIsLocked = true;
}
else
{
Cursor.lockState = CursorLockMode.None;
cursorIsLocked = false;
}
}
}
}