Issue with AddForce to player object in Unity

  Kiến thức lập trình

Im having a problem with addForce to player rigidbody. The issue is i made playerMovement with changing velocity and it is constantly overwritting player velocity and then when i want to addForce to player it is instanty overwritten. Problem is in the first if statement both of those playerRb.velocity

private void DefaultMoveRigidBody()
{
    Vector3 move = new Vector3(movementInput.x, 0, movementInput.y);
    Vector3 MoveVector = transform.TransformDirection(move) * movementSpeed;
    slopeMovementDirection = Vector3.ProjectOnPlane(MoveVector, slopeHit.normal);

    if (Physics.CheckSphere(FeetTransform.position, 1f, layerMask) && canJump && OnSlope())
    {
        playerRb.velocity = slopeMovementDirection;
    }
    else
    {
        playerRb.velocity = new Vector3(MoveVector.x, playerRb.velocity.y, MoveVector.z);
        Debug.Log(playerRb.velocity);
    }

    if (jumped && Physics.CheckSphere(FeetTransform.position, 1f, layerMask) && canJump)
    {
        canJump = false;
        jumpTimer = 0.5f;
        playerRb.velocity = new Vector3(playerRb.velocity.x, 0, playerRb.velocity.z);
        playerRb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
    }
    
    if (!canJump)
    {
        if (jumpTimer <= 0f)
        {
            canJump = true;
            jumpTimer = 0.5f;
        }
        else
        {
            jumpTimer -= Time.deltaTime;
        }
    }

    if (move != Vector3.zero)
    {
        Quaternion toRotation = Quaternion.LookRotation(-move, Vector3.up);
        gameObject.transform.GetChild(0).transform.localRotation = Quaternion.RotateTowards(gameObject.transform.GetChild(0).transform.localRotation, toRotation, rotationSpeed * Time.deltaTime);
    }
}

rb.AddForce is in another file with ForceMode.Impulze.
My goal is to push player on contact.

Is there some way to calculate final velocity or should i try different method of player movement?

New contributor

realsrbic is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT