Untitled
unknown
plain_text
a year ago
3.6 kB
32
Indexable
using TMPro;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.EventSystems;
public class PlaayerMovement : MonoBehaviour
{
[Header("Movement")]
public float groundSpeed = 10f;
public float airSpeed = 8f;
public float groundDrag = 7f;
public float airControl;
public float jumpForce = 12f;
public float jumpCooldown = 0.25f;
public bool readyToJump;
[Header("Ground Check")]
public LayerMask whatIsGround;
private bool isGrounded;
[Header("Landing")]
public float rideHeight = 2f;
private RaycastHit rayHit;
private bool rayDidHit;
private float springForce;
private bool useSpringForce;
public float rideSpringStrength = 300f;
public float rideSpringDamper = 15f;
public Transform orientation;
float horizontalInput;
float verticalInput;
Vector3 moveDir;
Rigidbody rb;
private void Start()
{
readyToJump = true;
rb = GetComponent<Rigidbody>();
rb.freezeRotation = true;
useSpringForce = true;
}
private void Update()
{
isGrounded = Physics.Raycast(transform.position, Vector3.down, rideHeight, whatIsGround);
rayDidHit = Physics.Raycast(transform.position, Vector3.down, out rayHit, rideHeight, whatIsGround);
MyInput();
SpeedControl();
if (isGrounded)
rb.linearDamping = groundDrag;
else
rb.linearDamping = 0;
}
private void FixedUpdate()
{
MovePlayer();
SmoothLand();
}
private void MyInput()
{
horizontalInput = Input.GetAxisRaw("Horizontal");
verticalInput = Input.GetAxisRaw("Vertical");
if (Input.GetKey(KeyCode.Space) && readyToJump && isGrounded)
{
readyToJump = false;
Jump();
Invoke(nameof(ResetJump), jumpCooldown);
}
}
private void MovePlayer()
{
moveDir = orientation.forward * verticalInput + orientation.right * horizontalInput;
if (isGrounded)
rb.AddForce(moveDir.normalized * groundSpeed * 10f, ForceMode.Force);
else if (!isGrounded)
rb.AddForce(moveDir.normalized * airSpeed * 10f * airControl, ForceMode.Force);
}
private void SpeedControl()
{
Vector3 flatVel = new Vector3(rb.linearVelocity.x, 0f, rb.linearVelocity.z);
float speedLimit = isGrounded ? groundSpeed : airSpeed;
if (flatVel.magnitude > groundSpeed)
{
Vector3 limitedVel = flatVel.normalized * groundSpeed;
rb.linearVelocity = new Vector3(limitedVel.x, rb.linearVelocity.y, limitedVel.z);
}
}
private void Jump()
{
useSpringForce = false;
rb.linearVelocity = new Vector3(rb.linearVelocity.x, 0f, rb.linearVelocity.z);
rb.AddForce(transform.up * jumpForce, ForceMode.Impulse);
}
private void ResetJump()
{
readyToJump = true;
useSpringForce = true;
}
private void SmoothLand()
{
if (rayDidHit && useSpringForce)
{
Vector3 vel = rb.linearVelocity;
Vector3 rayDir = Vector3.down;
float rayDirVel = Vector3.Dot(rayDir, vel);
float relVel = rayDirVel;
float x = rayHit.distance - rideHeight;
springForce = (x * rideSpringStrength) - (relVel * rideSpringDamper);
rb.AddForce(rayDir * springForce);
}
Debug.Log(rayHit.distance);
Debug.Log(springForce);
}
}
Editor is loading...
Leave a Comment