unity3D技术分享Unity3D与游戏开发

Unity3D 学习笔记(三) 增加跳跃

2020-02-22  本文已影响0人  Never肥宅

补充按键 public string keyJump = "space";

检测按键的下降沿

jump = Input.GetKeyDown(keyJump);

或者

Unity3D 学习笔记 增加跳跃

加入Jump动画,transition条件为trigger的Jump

在动画控制脚本中

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;

}

加入跳跃控制脚本

但是空中需要按键保持速度,如果要修正为空中时不受方向控制并能保持惯性还需要其他操作。

先添加是否落地的判断。

给plane的layer设定为Ground

Unity3D 学习笔记 增加跳跃

创建状态机进入脚本和退出脚本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 学习笔记 增加跳跃

在胶囊添加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()

{

//顶点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里添加对应函数

public void IsOnGround()

{

print("IsOnGround");

}

public void IsNotOnGround()

{

print("IsNotOnGround");

}

Unity3D 学习笔记 增加跳跃

正确显示是否在ground上

Unity3D 学习笔记 增加跳跃

添加falling动画

Unity3D 学习笔记 增加跳跃

添加OnGround的bool条件

设置好状态机循环哪个需要OnGround哪个不需要

在函数中添加对应的bool设置

public void IsOnGround()

{

print("IsOnGround");

anim.SetBool("OnGround",true);

}

public void IsNotOnGround()

{

print("IsNotOnGround");

anim.SetBool("OnGround",false);

}

接下来添加空中的惯性以及控制禁止操控

playerinput中添加

public bool inputEnable;

Unity3D 学习笔记 增加跳跃

只有使能时才能计算

public void OnGround()

{

print("On Ground");

pi.inputEnable = true;

}

public void ExitGround()

{

print("Exit Ground");

pi.inputEnable = false;

}

添加inputenable的赋值

运行游戏,可以正常工作

上一篇 下一篇

猜你喜欢

热点阅读