Моя механика нажатия зависит от частоты кадров

У меня проблемы с взаимодействием CharacterController с твердыми телами. Это вроде бы не работает, но только при 60 кадрах в секунду и дает странное поведение, когда я включаю v-sync или когда частота кадров низкая / очень высокая. У меня есть код для взаимодействия между CharacterController и твердыми телами, и я создал функцию под названием PushStates, которая загружается в функцию обновления.

void OnControllerColliderHit(ControllerColliderHit hit)
{
    Rigidbody body = hit.collider.attachedRigidbody;

    if (body == null || body.isKinematic)
        return;

    if (hit.moveDirection.y < -.3f)
        return;

    Vector3 pushDirection = new Vector3(hit.moveDirection.x, 0, hit.moveDirection.z);
    body.velocity = pushForce * pushDirection * Time.deltaTime;
}

Здесь у меня есть код, относящийся к моей механике толчка. Еще одна вещь, которая пока не работает, - это снятие всех сил с твердого тела, когда игрок перестает двигаться. Это приводит к тому, что pushableObject все еще удаляется от игрока примерно на пару сантиметров, и я также не уверен, почему он не работает.

public void PushStates() {
    // Creating the raycast origin Vector3's
    Vector3 forward = transform.TransformDirection(Vector3.forward) * distanceForPush;
    Vector3 middle = controller.transform.position - new Vector3(0, -controller.height / 2, 0);

    // Inspector bool
    if (pushRay)
    {
        Debug.DrawRay(middle, forward, Color.cyan);
    }

    // Force the pushForce and movementSpeed to normal when the player is not pushing
    pushForce = 0f;
    movementSpeed = walkSpeed;

    // Draws a raycast in front of the player to check if the object in front of the player is a pushable object
    if (Physics.Raycast(middle, forward, out hit, distanceForPush))
    {
        if (InputManager.BButton() && playerIsInPushingTrigger)
        {
            PushableInfo();

            playerIsPushing = true;
            anim.SetBool("isPushing", true);

            if (hit.collider.tag == "PushableLight")
            {
                pushForce = playerPushForceLight;
                movementSpeed = pushSpeedLight;
            }
            else if (hit.collider.tag == "PushableHeavy")
            {
                pushForce = playerPushForceHeavy;
                movementSpeed = pushSpeedHeavy;
            }

            // Checks the players speed now instead off movement. This is neccesary when the player is pushing a pushable into a collider. 
            // The player and pushable never stop moving because of force.
            if (currentSpeed < 0.15f)
            {
                //Removes all remaining velocity, when the player stops pushing
                pushableObjectRB.velocity = Vector3.zero;
                pushableObjectRB.angularVelocity = Vector3.zero;

                anim.SetFloat("pushSpeedAnim", 0f);
            }
            else
            {
                // Calls a rotation method
                PushingRot();
                if (hit.collider.tag == "PushableLight")
                {
                    anim.SetFloat("pushSpeedAnim", pushSpeedAnimLight);
                }
                else if (hit.collider.tag == "PushableHeavy")
                {
                    anim.SetFloat("pushSpeedAnim", pushSpeedAnimHeavy);
                }
            }
        }
        else
        {
            anim.SetBool("isPushing", false);
            pushForce = 0f;
            movementSpeed = walkSpeed;
            playerIsPushing = false;
        }
    }
    else
    {
        anim.SetBool("isPushing", false);
        playerIsPushing = false;
    }

    // Setting the time it takes to rotate when pushing
    AnimatorStateInfo stateInfo = anim.GetCurrentAnimatorStateInfo(0);
    if (stateInfo.fullPathHash == pushStateHash)
    {
        turnSmoothTime = maxTurnSmoothTimePushing;
    }
    else
    {
        turnSmoothTime = 0.1f;
    }
}

person Quincy Norbert    schedule 21.02.2019    source источник
comment
Что произойдет, если вы вызовете свой код в FixedUpdate, а не в Update?   -  person Joe Sewell    schedule 21.02.2019
comment
Вы имеете в виду функцию pushStates? Изменить: Быстрый тест, теперь я могу нажимать только на половину единицы, а затем он останавливается / застревает.   -  person Quincy Norbert    schedule 21.02.2019
comment
Вы не должны умножать на Time.deltaTime в OnControllerColliderHit. Документация для этой функции точно описывает то, что вы пытаетесь здесь сделать.   -  person Foggzie    schedule 21.02.2019
comment
Я действительно добавил к нему Time.deltaTime, и удаление его и изменение некоторых значений помогло! Большое спасибо.   -  person Quincy Norbert    schedule 21.02.2019


Ответы (1)


Удаление Time.deltaTime из скорости твердого тела и изменение некоторых настроек в инспекторе, то есть (pushForce, pushSpeed), решило мою проблему.

person Quincy Norbert    schedule 21.02.2019