Unity中不用自带重力实现跳跃的方法
发表于2018-10-10
做游戏开发,少不了跳跃这个功能,如果想不使用自带的重力系统来完成跳跃动作改怎么做,如果是这种需求就需要考虑下面三种情况,通过分别介绍这三种跳跃下的情况来实现不用自带重力系统完成跳跃的方法,代码分为三部分:
Update()中的输入判定代码
LateUpdate()中的跳跃实现部分
OnCollisionEnter()与OnCollisionExit()的落地&离地检测部分
1、当玩家按下跳跃键时进入跳跃状态并判断当前的水平速度。
//跳跃判定
if (Input.GetButtonDown("Jump") &&nextJump) //不能在落地前跳跃
if (currentBaseState.fullPathHash == walkingState||
currentBaseState.fullPathHash == runningState||
currentBaseState.fullPathHash == standingState)//不能在动画完成前跳跃
{
nextJump = false;//落地前无法再次起跳
GameManager.isJumping = true;//进入跳跃状态
if (GameManager.isStanding)
{
jumpV_x = 0;//处于站立状态时水平初速度为0
GameManager.isStanding = false;//改变当前状态由站立到跳跃,下同
}
if (GameManager.isWalking)
{
jumpV_x = Haxis * moveSpeed;
GameManager.isWalking = false;
}
if (GameManager.isRunning) //加速跳跃
{
jumpV_x = Haxis * moveSpeed;
jumpVelocity = GameManager.jumpVelocity * GameManager.jumpMultiple;//加速跳跃时竖向分速度也提高
GameManager.isRunning = false;
}
}
2、当跳跃状态==true时每帧移动相应的竖向,水平距离。
private void LateUpdate()
{
transform.Translate(Vector3.right * Time.deltaTime * moveSpeed * Haxis); //角色移动实现
if (GameManager.isJumping) //跳跃实现
{
jumpHight += jumpVelocity * Time.deltaTime * jumpSpeed;
jumpVelocity = jumpVelocity - 9.8f * Time.deltaTime * jumpSpeed;
currentPosition.y = jumpHight;
currentPosition.x = privousPosition.x + Time.deltaTime * jumpV_x; //空中水平移动实现
transform.position = currentPosition;
}
3、落地以后退出跳跃状态,允许进行下次跳跃,并将跳跃速度的全局变量回归初始值以便下次跳跃。
void OnCollisionEnter(Collision collider)
{
//落地检测
if (collider.gameObject.tag == "Ground")
{
nextJump = true;
GameManager.isGround = true;
GameManager.isJumping = false;
//落地还原速度
moveSpeed = GameManager.moveSpeed;
jumpVelocity = GameManager.jumpVelocity;
jumpHight = 0;
jumpV_x = 0;
Debug.Log("ground!");
}
}
void OnCollisionExit(Collision collider)
{
//离地检测
if (collider.gameObject.tag == "Ground")
GameManager.isGround = false;
Debug.Log("offground!");
}
