Why does my player "jump" on his own when touching short objects?

Why does my player “jump” on his own? In the gif you can see a gray rectangle and what happens when the player touches it - my player kind of jumped, I didn’t jump even once, there’s no such possibility in my code.
2024-11-2718-59-24-ezgif.com-video-to-gif-converter

Code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class Gracz : MonoBehaviour
{
    public Camera playerCamera;
    public float walkSpeed = 6f;
    public float runSpeed = 12f;
    public float jumpPower = 7f;
    public float gravity = 20f;

    public float lookSpeed = 2f;
    public float lookXLimit = 45f;

    public bool canMove = true; // Kontroluje możliwość ruchu gracza

    public float bobFrequency = 5f;
    public float bobMagnitude = 0.1f;

    private Vector3 moveDirection = Vector3.zero;
    private float rotationX = 0;
    private bool isGrounded = false;

    private Rigidbody rb;
    private CapsuleCollider capsuleCollider;

    private Vector3 cameraOriginalPosition;

    private KeyCode forwardKey;
    private KeyCode backKey;
    private KeyCode leftKey;
    private KeyCode rightKey;
    private KeyCode jumpKey;

    private bool isWalking = false;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
        rb.freezeRotation = true;

        capsuleCollider = GetComponent<CapsuleCollider>();
        if (capsuleCollider != null)
        {
            // Dodajemy materiał fizyczny o zerowym tarciu
            PhysicMaterial noFriction = new PhysicMaterial();
            noFriction.dynamicFriction = 0f;
            noFriction.staticFriction = 0f;
            noFriction.frictionCombine = PhysicMaterialCombine.Minimum;
            capsuleCollider.material = noFriction;
        }

        Cursor.lockState = CursorLockMode.Locked;
        Cursor.visible = false;

        cameraOriginalPosition = playerCamera.transform.localPosition;
    }

    void Update()
    {
        forwardKey = (KeyCode)System.Enum.Parse(typeof(KeyCode), PlayerPrefs.GetString("Forward", "W"));
        backKey = (KeyCode)System.Enum.Parse(typeof(KeyCode), PlayerPrefs.GetString("Back", "S"));
        leftKey = (KeyCode)System.Enum.Parse(typeof(KeyCode), PlayerPrefs.GetString("Left", "A"));
        rightKey = (KeyCode)System.Enum.Parse(typeof(KeyCode), PlayerPrefs.GetString("Right", "D"));
        jumpKey = (KeyCode)System.Enum.Parse(typeof(KeyCode), PlayerPrefs.GetString("Jump", "Space"));

        HandleMovement();
        HandleJumping();
        HandleRotation();
        HandleCameraBob();
    }

    void HandleMovement()
    {
        Vector3 forward = transform.TransformDirection(Vector3.forward);
        Vector3 right = transform.TransformDirection(Vector3.right);

        bool isRunning = Input.GetKey(KeyCode.LeftShift);

        float speedX = 0;
        float speedY = 0;

        if (Input.GetKey(forwardKey)) speedX = isRunning ? runSpeed : walkSpeed;
        if (Input.GetKey(backKey)) speedX = -(isRunning ? runSpeed : walkSpeed);
        if (Input.GetKey(rightKey)) speedY = isRunning ? runSpeed : walkSpeed;
        if (Input.GetKey(leftKey)) speedY = -(isRunning ? runSpeed : walkSpeed);

        Vector3 horizontalMovement = (forward * speedX + right * speedY);

        if (isGrounded)
        {
            // Na ziemi uwzględniamy pełen ruch
            moveDirection = horizontalMovement;
        }
        else
        {
            // W powietrzu ograniczamy wpływ ruchu poziomego
            moveDirection += horizontalMovement * 0.1f;
            moveDirection = Vector3.ClampMagnitude(moveDirection, runSpeed); // Ograniczenie prędkości
        }

        moveDirection.y = rb.velocity.y; // Zachowujemy aktualną prędkość w osi Y
        rb.velocity = moveDirection;

        if (horizontalMovement.magnitude > 0 && !isRunning)
        {
            isWalking = true; // Chodzenie
        }
        else
        {
            isWalking = false; // Nie chodzenie
        }
    }

    void HandleJumping()
    {
        isGrounded = Physics.Raycast(transform.position, Vector3.down, capsuleCollider.bounds.extents.y + 0.1f);
    }

    void HandleRotation()
    {
        if (canMove)
        {
            rotationX += -Input.GetAxis("Mouse Y") * lookSpeed;
            rotationX = Mathf.Clamp(rotationX, -lookXLimit, lookXLimit);
            playerCamera.transform.localRotation = Quaternion.Euler(rotationX, 0, 0);
            transform.rotation *= Quaternion.Euler(0, Input.GetAxis("Mouse X") * lookSpeed, 0);
        }
    }

    void HandleCameraBob()
    {
        if (isWalking)
        {
            float bobFactorX = Mathf.Sin(Time.time * bobFrequency) * bobMagnitude;
            float bobFactorY = Mathf.Cos(Time.time * bobFrequency * 2) * bobMagnitude * 0.5f;
            Vector3 bobOffsetVector = new Vector3(bobFactorX, bobFactorY, 0);

            playerCamera.transform.localPosition = Vector3.Lerp(playerCamera.transform.localPosition, cameraOriginalPosition + bobOffsetVector, Time.deltaTime * 5f);
        }
        else
        {
            playerCamera.transform.localPosition = Vector3.Lerp(playerCamera.transform.localPosition, cameraOriginalPosition, Time.deltaTime * 5f);
        }
    }

    void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("lawa"))
        {
            SceneManager.LoadScene(9);
        }
    }
}

It’s normal for a big slippery capsule to go flying into the air when it hits a curb. This would also happen in reality. If you don’t like it then you’ll need to make your character always hover slightly above the ground.

BTW - You could move your code that gets the key config from PlayerPrefs into Start().

And on line 129 you should use MoveRotation to smoothly rotate your player. Like so:

rb.MoveRotation(transform.rotation*Quaternion.Euler(0, Input.GetAxis("Mouse X") * lookSpeed, 0));

Thank you for your reply! How can I make the player float above the ground if i’m using rigidbody, if that’s what you meant? And I want my player to be able to climb onto this type of objects but without the “jumping” effect, won’t this make him unable to do it?

You add a hover height property and constantly adjust the vertical velocity to maintain the required height, but only when the ground is near.

Example:

using UnityEngine;
public class FPSRigidController : MonoBehaviour     // Minimalist rigidbody controller with the ability to run, jump and crouch. It will also smoothly climb stairs and vault over low objects.
{   // Place the script onto a rigidbody sphere and enable interpolation and set the angular drag to 20. Also, make the camera a child of the sphere.
    Rigidbody rb;
    float headOffset = 0.5f;
    void Start()
    {
        rb = GetComponent<Rigidbody>();
        Cursor.lockState = CursorLockMode.Locked;
        rb.centerOfMass = -Vector3.up * 0.7f;
    }
    void FixedUpdate()
    {
        Vector3 force = (transform.right * Input.GetAxisRaw("Horizontal") + transform.forward * Input.GetAxisRaw("Vertical")).normalized;
        if (Physics.SphereCast(transform.position, 0.45f, Vector3.down, out RaycastHit hit, 1.3f))  // are we grounded?
        {
            if (Input.GetKey(KeyCode.Space) && Mathf.Abs(rb.velocity.y) < 0.5f) headOffset = -headOffset;    // croucher
            force = Vector3.ProjectOnPlane(force, hit.normal);
            if (Input.GetKey(KeyCode.LeftShift)) force *= 2;  // run?
            rb.AddForce((force * 20) - rb.velocity * 4);  // add the main force for movement but also bring the character to a stop when not trying to move
            rb.AddForce(Vector3.up * ((1.5f + headOffset) - ((transform.position.y + rb.velocity.y * 0.2f) - hit.point.y)) * 30);     // hover
            if (Input.GetMouseButton(1)) rb.AddForce(Vector3.up * (6 - Vector3.Dot(Vector3.up, rb.velocity)), ForceMode.Impulse);      // jumper
        }
        rb.AddRelativeTorque(Input.GetAxis("Mouse Y") * 10f, Input.GetAxis("Mouse X") * 10f, Mathf.DeltaAngle(transform.localEulerAngles.z, 0) * 0.8f); // look around using the mouse
    }
}

1 Like

That’s a good idea, i’ll check it out!

It worked, thank you