키를 누르는 시간에 따라 점프의 높이에 변화를 줘보자.
이전의 점프 스크립트를 수정한다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
// ...생략
// 점프 높이
public float jumpHeight = 2;
// 작용하는 중력
public float gravityMultiplier = 1.5f;
// ...생략
void Update()
{
// ...생략
// 작용하는 중력 계산
float gravity = Physics.gravity.y * gravityMultiplier;
// 점프 시작, 위쪽 방향이동 체크, 점프 버튼을 더 이상 누르지 않는지
// 세가지 조건이 충족되면 중력값을 두배로 늘린다.
if(isJumping && ySpeed > 0 && Input.GetButton("Jump") == false)
{
gravity *= 2;
}
ySpeed += gravity * Time.deltaTime;
// ...생략
if (Time.time - lastGroundedTime <= jumpButtonGracePeriod)
{
characterController.stepOffset = originalStepOffset;
ySpeed = -0.8f;
animator.SetBool("isGrounded", true);
isGrounded = true;
animator.SetBool("isJumping", false);
isJumping = false;
animator.SetBool("isFalling", false);
if (Time.time - jumpButtonPressedTime <= jumpButtonGracePeriod)
{
// jumpHeight만큼 점프하도록하는 공식
ySpeed = Mathf.Sqrt(-jumpHeight * 2 * gravity);
animator.SetBool("isJumping", true);
isJumping = true;
lastGroundedTime = null;
jumpButtonPressedTime = null;
}
}
else
{
characterController.stepOffset = 0;
animator.SetBool("isGrounded", false);
isGrounded = false;
if ((isJumping && ySpeed < 0) || (ySpeed < -2.5f))
{
animator.SetBool("isFalling", true);
}
}
// ...생략
}
// ...생략
}
gravityMultiplier 값에 따라 체공 시간이 달라진다
MathF.Sqrt
public static float Sqrt (float x);
제곱근을 반환하는 함수