D
D
Dmitry Mironov2020-06-22 13:19:46
C++ / C#
Dmitry Mironov, 2020-06-22 13:19:46

How to remove character twitching when trying to jump onto a ledge?

I made a character with first person controls. But it so happens that if you continue to go into the box and jump, then the character starts to twitch when he reaches the top of the box with the middle of his body and as a result he does not jump and falls. If you do not leave that place and press the jump button without moving, then the character will jump normally. Does anyone know how to solve this problem?

Here is the code:

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

public class Movement : MonoBehaviour
{
    public CharacterController controller;

    public float speed = 12f;
    public float gravity = -9.81f;
    public float jumpHeight = 3f;

    public float sphereRadius = 0.1f;
    private AudioSource m_AudioSourse;

    private Vector3 velocity;

    public Transform groundChecker;
    public Transform ceilingChecker;
    public LayerMask ground;

    public AudioClip[] step;

    bool isGrounded;
    bool isCeiling;
    bool inWater;
    private void Start()
    {
        m_AudioSourse = GetComponent<AudioSource>();
    }
    void Update()
    {
        isGrounded = Physics.CheckSphere(groundChecker.position, sphereRadius, ground);
        isCeiling = Physics.CheckSphere(ceilingChecker.position, sphereRadius, ground);
        if(isCeiling)
        {
            velocity.y = -2f;
        }

        if(isGrounded && velocity.y < 0)
        {
            velocity.y = -4f;
        }

        if(Input.GetButtonDown("Jump") && isGrounded)
        {
            velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
        }

        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");
        if(x!=0||z!=0)
        {
            PlayStepSound();
        }

        Vector3 move = transform.right * x + transform.forward * z;

        if (Input.GetButton("Run"))
        {
            move *= 1.5f;
        }

        controller.Move(move * speed * Time.deltaTime);

        velocity.y += gravity * Time.deltaTime;
        controller.Move(velocity * Time.deltaTime);
        Debug.Log(velocity.y);
    }
    void PlayStepSound()
    {
        float pitchVal;
        if (Input.GetButton("Run"))
            pitchVal = 1.5f;
        else
            pitchVal = 1f;
        if (!m_AudioSourse.isPlaying && isGrounded)
        {
            int n = Random.Range(0, step.Length);
            m_AudioSourse.clip = step[n];
            m_AudioSourse.pitch = pitchVal;
            m_AudioSourse.Play();
        }
    }
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question