Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- public class PlayerController : MonoBehaviour
- {
- public float moveSpeed = 5f;
- public LayerMask floorLayerMask; // Set this to the layer your floor colliders are on
- public float checkDistance = 1f; // Distance to check for the floor
- private void Start()
- {
- }
- private void Awake()
- {
- }
- void Update()
- {
- float horizontal = Input.GetAxis("Horizontal");
- float vertical = Input.GetAxis("Vertical");
- Vector3 direction = new Vector3(horizontal, 0, vertical).normalized;
- Vector3 newPosition = transform.position + direction * moveSpeed * Time.deltaTime;
- if (direction.magnitude >= 0.1f && IsFloorBelow(newPosition))
- {
- float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg;
- transform.rotation = Quaternion.Euler(0, targetAngle, 0);
- Vector3 moveDirection = Quaternion.Euler(0, targetAngle, 0) * Vector3.forward;
- transform.position += moveDirection * moveSpeed * Time.deltaTime;
- }
- }
- bool IsFloorBelow(Vector3 position)
- {
- Ray ray = new Ray(position + Vector3.up, Vector3.down);
- return Physics.Raycast(ray, checkDistance, floorLayerMask);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement