Advertisement
MatiGe

Player

Aug 18th, 2024
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.34 KB | Gaming | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class PlayerController : MonoBehaviour
  6. {
  7.     public float moveSpeed = 5f;
  8.     public LayerMask floorLayerMask; // Set this to the layer your floor colliders are on
  9.     public float checkDistance = 1f; // Distance to check for the floor
  10.  
  11.     private void Start()
  12.     {
  13.  
  14.     }
  15.  
  16.     private void Awake()
  17.     {
  18.        
  19.  
  20.  
  21.     }
  22.  
  23.     void Update()
  24.     {
  25.         float horizontal = Input.GetAxis("Horizontal");
  26.         float vertical = Input.GetAxis("Vertical");
  27.  
  28.         Vector3 direction = new Vector3(horizontal, 0, vertical).normalized;
  29.         Vector3 newPosition = transform.position + direction * moveSpeed * Time.deltaTime;
  30.  
  31.  
  32.         if (direction.magnitude >= 0.1f && IsFloorBelow(newPosition))
  33.         {
  34.             float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg;
  35.             transform.rotation = Quaternion.Euler(0, targetAngle, 0);
  36.  
  37.             Vector3 moveDirection = Quaternion.Euler(0, targetAngle, 0) * Vector3.forward;
  38.             transform.position += moveDirection * moveSpeed * Time.deltaTime;
  39.         }
  40.     }
  41.  
  42.     bool IsFloorBelow(Vector3 position)
  43.     {
  44.         Ray ray = new Ray(position + Vector3.up, Vector3.down);
  45.         return Physics.Raycast(ray, checkDistance, floorLayerMask);
  46.     }
  47. }
  48.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement