Когда я прыгаю, игрок теряет прежнюю скорость и создается ощущение, что вы натыкаетесь на невидимую стену.
Я пробовал изменить сопротивление, элементы управления наклоном и принцип работы прыжка, чтобы безрезультатно. Я также пробовал использовать чатгпт, но ничего не помогло. Я также был бы признателен, если бы были какие-нибудь более эффективные способы переместить плеер так, как это сделал я.
using UnityEngine;
using System.Collections;
public class PlayerMovement : MonoBehaviour
{
[Header("Movement Settings")]
public float walkSpeed = 5f;
public float sprintSpeed = 10f;
public float crouchSpeed = 2f;
public Transform orientation;
public float groundDrag = 5f;
public float airDrag = 0f;
public float moveSmoothing = 0.1f;
public float maxSpeed = 10f;
[Header("Ground Check")]
public float groundCheckRadius = 0.5f;
public LayerMask groundLayer;
private bool grounded;
private bool wasGrounded;
[Header("Slope Handling")]
public float maxSlopeAngle = 45f;
private bool exitingSlope;
private bool onSlope;
private RaycastHit slopeHit;
private Vector3 slopeNormal;
private float slopeRayLength = 2f; // Longer ray length for better accuracy
private float groundRayOffset = 0.5f; // Height offset for ray origin
private int groundRayCount = 3; // Number of ground check rays
[Header("Player Jumping")]
public float jumpForce = 10f;
public float jumpCooldown = 1f;
public float airMultiplier = 0.25f;
private Vector3 storedVelocity;
[Header("Crouching")]
public float crouchYScale = 0.5f;
private float startYScale;
[Header("Keybinds")]
public KeyCode jumpKey = KeyCode.Space;
public KeyCode sprintKey = KeyCode.LeftShift;
public KeyCode crouchKey = KeyCode.LeftControl;
private Rigidbody rb;
private float moveSpeed;
private float horizontalInput;
private float verticalInput;
private bool readyToJump = true;
private Vector3 moveDirection;
public MovementState state;
public enum MovementState
{
walking,
sprinting,
crouching,
air
}
private void Start()
{
rb = GetComponent();
rb.freezeRotation = true;
rb.constraints = RigidbodyConstraints.FreezeRotationX |
RigidbodyConstraints.FreezeRotationY |
RigidbodyConstraints.FreezeRotationZ;
startYScale = transform.localScale.y;
rb.drag = groundDrag;
}
private bool IsGrounded()
{
// Ground check using multiple raycasts to ensure accuracy
bool isGrounded = false;
float rayLength = slopeRayLength;
Vector3 rayOrigin = transform.position + Vector3.up * groundRayOffset;
for (int i = -1; i 0 && angle 0)
rb.AddForce(Vector3.down * 80f, ForceMode.Force);
}
else if (grounded)
{
Vector3 targetPosition = transform.position + moveDirection * moveSpeed * Time.fixedDeltaTime;
rb.MovePosition(Vector3.Lerp(transform.position, targetPosition, moveSmoothing));
}
else
{
rb.AddForce(moveDirection * moveSpeed * airMultiplier, ForceMode.Force); // Airborne movement
}
}
private void CapSpeed()
{
float currentSpeed = rb.velocity.magnitude;
if (currentSpeed > maxSpeed)
{
rb.velocity = rb.velocity.normalized * maxSpeed; // Limit speed to avoid excessive acceleration
}
}
private void Jump() {
// Keep horizontal velocity, reset only vertical component to 0 before jump
Vector3 horizontalVelocity = new Vector3(rb.velocity.x, rb.velocity.z); // Remove Y component
// Set the new velocity with preserved horizontal components
rb.velocity = new Vector3(horizontalVelocity.x, 0, horizontalVelocity.y);
// Apply jump force
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
Debug.Log("jump");
}
private IEnumerator JumpCooldown()
{
yield return new WaitForSeconds(jumpCooldown);
readyToJump = true;
}
private IEnumerator SmoothDragChange(float newDrag, float duration)
{
float startDrag = rb.drag;
float time = 0f;
while (time < duration)
{
rb.drag = Mathf.Lerp(startDrag, newDrag, time / duration);
time += Time.fixedDeltaTime;
yield return new WaitForSeconds(Time.fixedDeltaTime);
}
rb.drag = newDrag;
}
private void OnLanding()
{
storedVelocity = rb.velocity;
Invoke("RestoreVelocity", 0.1f);
rb.drag = groundDrag; // Restore drag upon landing
Invoke(nameof(ResetGroundDrag), 0.1f); // Slight delay to smooth landing
}
private void RestoreVelocity()
{
rb.velocity = storedVelocity;
}
private void ResetGroundDrag()
{
rb.drag = groundDrag;
}
private void OnDrawGizmos()
{
Gizmos.color = Color.red;
Vector3 rayOrigin = transform.position + Vector3.up * groundRayOffset;
float rayLength = slopeRayLength;
for (int i = -1; i
Подробнее здесь: https://stackoverflow.com/questions/784 ... t-jumps-it
Я делаю игру на Unity, и если я закодировал этот контроллер игрока, но когда он прыгает, он теряет мою скорость. ⇐ C#
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Почему Unity преобразует мою скорость вперед в горизонтальную скорость? [закрыто]
Anonymous » » в форуме C# - 0 Ответы
- 78 Просмотры
-
Последнее сообщение Anonymous
-