Unity3D 學(xué)習(xí)筆記(三) 增加跳躍

補(bǔ)充按鍵 public string keyJump = "space";

檢測按鍵的下降沿

jump = Input.GetKeyDown(keyJump);

或者

Unity3D 學(xué)習(xí)筆記 增加跳躍

加入Jump動(dòng)畫,transition條件為trigger的Jump

在動(dòng)畫控制腳本中

if(pi.jump)

{

anim.SetTrigger("Jump");

thrust = new Vector3(0,JumpFactor,0);

}

void FixedUpdate()

{

rigid.velocity = new Vector3(bodyVelocity.x,rigid.velocity.y,bodyVelocity.z) + thrust;

thrust = Vector3.zero;

}

加入跳躍控制腳本

但是空中需要按鍵保持速度,如果要修正為空中時(shí)不受方向控制并能保持慣性還需要其他操作。

先添加是否落地的判斷。

給plane的layer設(shè)定為Ground

Unity3D 學(xué)習(xí)筆記 增加跳躍

創(chuàng)建狀態(tài)機(jī)進(jìn)入腳本和退出腳本FSMENTER FSMEXIT

public class FSMOnEnter : StateMachineBehaviour

{

public string[] onEnterMessage;

override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)

{

foreach(var msg in onEnterMessage)

{

animator.gameObject.SendMessageUpwards(msg);

}

}

}

Unity3D 學(xué)習(xí)筆記 增加跳躍

在膠囊添加OnGroundSensor腳本

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

public class OnGroundSensor : MonoBehaviour

{

public CapsuleCollider cap;

public float offset = 0.1f;

private Vector3 point1;

private Vector3 point2;

private float radius;

// Start is called before the first frame update

void Start()

{

radius = cap.radius - 0.05f;

}

// Update is called once per frame

void FixedUpdate()

{

//頂點(diǎn)1,位置加上up方向上長度radius

point1 = transform.position + transform.up * (radius - offset);

point2 = transform.position + transform.up * (cap.height - offset);

Collider[] outputCols = Physics.OverlapCapsule(point1,point2,radius,LayerMask.GetMask("Ground"));

if (outputCols.Length != 0)

{

SendMessageUpwards("IsOnGround");

}

else

{

SendMessageUpwards("IsNotOnGround");

}

}

}

在ActorController里添加對(duì)應(yīng)函數(shù)

public void IsOnGround()

{

print("IsOnGround");

}

public void IsNotOnGround()

{

print("IsNotOnGround");

}

Unity3D 學(xué)習(xí)筆記 增加跳躍

正確顯示是否在ground上

Unity3D 學(xué)習(xí)筆記 增加跳躍

添加falling動(dòng)畫

Unity3D 學(xué)習(xí)筆記 增加跳躍

添加OnGround的bool條件

設(shè)置好狀態(tài)機(jī)循環(huán)哪個(gè)需要OnGround哪個(gè)不需要

在函數(shù)中添加對(duì)應(yīng)的bool設(shè)置

public void IsOnGround()

{

print("IsOnGround");

anim.SetBool("OnGround",true);

}

public void IsNotOnGround()

{

print("IsNotOnGround");

anim.SetBool("OnGround",false);

}

接下來添加空中的慣性以及控制禁止操控

playerinput中添加

public bool inputEnable;

Unity3D 學(xué)習(xí)筆記 增加跳躍

只有使能時(shí)才能計(jì)算

public void OnGround()

{

print("On Ground");

pi.inputEnable = true;

}

public void ExitGround()

{

print("Exit Ground");

pi.inputEnable = false;

}

添加inputenable的賦值

運(yùn)行游戲,可以正常工作

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容