当前位置: 首页 > news >正文

[Unity Demo]从零开始制作空洞骑士Hollow Knight第二集:通过InControl插件实现绑定玩家输入以及制作小骑士移动空闲动画

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录

  • 前言
  • 一、通过InControl插件实现绑定玩家输入
  • 二、制作小骑士移动和空闲动画
    • 1.制作动画
    • 2.玩家移动和翻转图像
    • 3.状态机思想实现动画切换
  • 总结


前言

好久没来CSDN看看,突然看到前两年自己写的文章从零开始制作空洞骑士只做了一篇就突然烂尾了,刚好最近开始学习做Unity,我决定重启这个项目,从零开始制作空洞骑士!第一集我们导入了素材和远程git管理项目,OK这期我们就从通过InControl插件实现绑定玩家输入以及制作小骑士移动和空闲动画。


一、通过InControl插件实现绑定玩家输入

其实这一部挺难的,因为InControl插件你在网上绝对不超过五个视频资料,但没办法空洞骑士就是用这个来控制键盘控制器输入的,为了原汁原味就只能翻一下InControl提供的Examples示例里学习。

学习完成后直接来看我写的InputHandler.cs和GameManager.cs

在GameManager.cs中我们暂且先只用实现一个单例模式:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class GameManager : MonoBehaviour
{private static GameManager _instance;public static GameManager instance{get{if(_instance == null){_instance = FindObjectOfType<GameManager>();}if (_instance == null){Debug.LogError("Couldn't find a Game Manager, make sure one exists in the scene.");}else if (Application.isPlaying){DontDestroyOnLoad(_instance.gameObject);}return _instance;}}private void Awake(){if(_instance != this){_instance = this;DontDestroyOnLoad(this);return;}if(this != _instance){Destroy(gameObject);return;}}}

 在来到InputHandler.cs之前,我们还需要创建映射表HeroActions:

using System;
using InControl;public class HeroActions : PlayerActionSet
{public PlayerAction left;public PlayerAction right;public PlayerAction up;public PlayerAction down;public PlayerTwoAxisAction moveVector;public HeroActions(){left = CreatePlayerAction("Left");left.StateThreshold = 0.3f;right = CreatePlayerAction("Right");right.StateThreshold = 0.3f;up = CreatePlayerAction("Up");up.StateThreshold = 0.3f;down = CreatePlayerAction("Down");down.StateThreshold = 0.3f;moveVector = CreateTwoAxisPlayerAction(left, right, up, down);moveVector.LowerDeadZone = 0.15f;moveVector.UpperDeadZone = 0.95f;}
}

OK到了最关键的InputHandler.cs了:

using System;
using System.Collections;
using System.Collections.Generic;
using GlobalEnums;
using InControl;
using UnityEngine;public class InputHandler : MonoBehaviour
{public InputDevice gameController;public HeroActions inputActions;public void Awake(){inputActions = new HeroActions();}public void Start(){MapKeyboardLayoutFromGameSettings();if(InputManager.ActiveDevice != null && InputManager.ActiveDevice.IsAttached){}else{gameController = InputDevice.Null;}Debug.LogFormat("Input Device set to {0}.", new object[]{gameController.Name});}
//暂时没有GameSettings后续会创建的,这里是指将键盘按键绑定到HeroActions 中private void MapKeyboardLayoutFromGameSettings(){AddKeyBinding(inputActions.up, "W");AddKeyBinding(inputActions.down, "S");AddKeyBinding(inputActions.left, "A");AddKeyBinding(inputActions.right, "D");}private static void AddKeyBinding(PlayerAction action, string savedBinding){Mouse mouse = Mouse.None;Key key;if (!Enum.TryParse(savedBinding, out key) && !Enum.TryParse(savedBinding, out mouse)){return;}if (mouse != Mouse.None){action.AddBinding(new MouseBindingSource(mouse));return;}action.AddBinding(new KeyBindingSource(new Key[]{key}));}}
 给我们的小骑士创建一个HeroController.cs,检测输入最关键的是一行代码:
move_input = inputHandler.inputActions.moveVector.Vector.x;
using System;
using System.Collections;
using System.Collections.Generic;
using HutongGames.PlayMaker;
using GlobalEnums;
using UnityEngine;public class HeroController : MonoBehaviour
{public ActorStates hero_state;public ActorStates prev_hero_state;public bool acceptingInput = true;public float move_input;public float RUN_SPEED = 5f;private Rigidbody2D rb2d;private BoxCollider2D col2d;private GameManager gm;private InputHandler inputHandler;private void Awake(){SetupGameRefs();}private void SetupGameRefs(){rb2d = GetComponent<Rigidbody2D>();col2d = GetComponent<BoxCollider2D>();gm = GameManager.instance;inputHandler = gm.GetComponent<InputHandler>();}void Start(){}void Update(){orig_Update();}private void orig_Update(){if (hero_state == ActorStates.no_input){}else if(hero_state != ActorStates.no_input){LookForInput();}}private void FixedUpdate(){if (hero_state != ActorStates.no_input){Move(move_input);}}private void Move(float move_direction){if(acceptingInput){rb2d.velocity = new Vector2(move_direction * RUN_SPEED, rb2d.velocity.y);}}private void LookForInput(){if (acceptingInput){move_input = inputHandler.inputActions.moveVector.Vector.x;}}
}[Serializable]
public class HeroControllerStates
{public bool facingRight;public bool onGround;public HeroControllerStates(){facingRight = true;onGround = false;}
}

记得一句话:FixedUpdate()处理物理移动,Update()处理逻辑 

二、制作小骑士移动和空闲动画

1.制作动画

        素材找到Idle和Walk文件夹,创建两个同名animation,sprite往上面一放自己就做好了。

        可能你注意到我没有给这两个动画连线,其实是我想做个动画状态机,通过核心代码

        animator.Play()来管理动画的切换。

2.玩家移动和翻转图像

我们还需要给小骑士添加更多的功能比如翻转图像:

using System;
using System.Collections;
using System.Collections.Generic;
using HutongGames.PlayMaker;
using GlobalEnums;
using UnityEngine;public class HeroController : MonoBehaviour
{public ActorStates hero_state;public ActorStates prev_hero_state;public bool acceptingInput = true;public float move_input;public float RUN_SPEED = 5f;private Rigidbody2D rb2d;private BoxCollider2D col2d;private GameManager gm;private InputHandler inputHandler;public HeroControllerStates cState;private HeroAnimatorController animCtrl;private void Awake(){SetupGameRefs();}private void SetupGameRefs(){if (cState == null)cState = new HeroControllerStates();rb2d = GetComponent<Rigidbody2D>();col2d = GetComponent<BoxCollider2D>();animCtrl = GetComponent<HeroAnimatorController>();gm = GameManager.instance;inputHandler = gm.GetComponent<InputHandler>();}void Start(){}void Update(){orig_Update();}private void orig_Update(){if (hero_state == ActorStates.no_input){}else if(hero_state != ActorStates.no_input){LookForInput();}}private void FixedUpdate(){if (hero_state != ActorStates.no_input){Move(move_input);if(move_input > 0f && !cState.facingRight ){FlipSprite();}else if(move_input < 0f && cState.facingRight){FlipSprite();}}}private void Move(float move_direction){if (cState.onGround){SetState(ActorStates.grounded);}if(acceptingInput){rb2d.velocity = new Vector2(move_direction * RUN_SPEED, rb2d.velocity.y);}}public void FlipSprite(){cState.facingRight = !cState.facingRight;Vector3 localScale = transform.localScale;localScale.x *= -1f;transform.localScale = localScale;}private void LookForInput(){if (acceptingInput){move_input = inputHandler.inputActions.moveVector.Vector.x;}}/// <summary>/// 设置玩家的ActorState的新类型/// </summary>/// <param name="newState"></param>private void SetState(ActorStates newState){if(newState == ActorStates.grounded){if(Mathf.Abs(move_input) > Mathf.Epsilon){newState  = ActorStates.running;}else{newState = ActorStates.idle;}}else if(newState == ActorStates.previous){newState = prev_hero_state;}if(newState != hero_state){prev_hero_state = hero_state;hero_state = newState;animCtrl.UpdateState(newState);}}private void OnCollisionEnter2D(Collision2D collision){if(collision.gameObject.layer == LayerMask.NameToLayer("Wall")){cState.onGround = true;}}private void OnCollisionStay2D(Collision2D collision){if (collision.gameObject.layer == LayerMask.NameToLayer("Wall")){cState.onGround = true;}}private void OnCollisionExit2D(Collision2D collision){if (collision.gameObject.layer == LayerMask.NameToLayer("Wall")){cState.onGround = false;}}
}[Serializable]
public class HeroControllerStates
{public bool facingRight;public bool onGround;public HeroControllerStates(){facingRight = true;onGround = false;}
}

创建命名空间GlobalEnums,创建一个新的枚举类型: 

using System;namespace GlobalEnums
{public enum ActorStates{grounded,idle,running,airborne,wall_sliding,hard_landing,dash_landing,no_input,previous}
}

3.状态机思想实现动画切换

有了这些我们就可以有效控制动画切换,创建一个新的脚本给Player:

可以看到我们创建了两个属性记录当前的actorState和上一个actorState来实现动画切换(后面会用到的)

using System;
using GlobalEnums;
using UnityEngine;public class HeroAnimatorController : MonoBehaviour
{private Animator animator;private AnimatorClipInfo[] info;private HeroController heroCtrl;private HeroControllerStates cState;private string clipName;private float currentClipLength;public ActorStates actorStates { get; private set; }public ActorStates prevActorState { get; private set; }private void Start(){animator = GetComponent<Animator>();heroCtrl = GetComponent<HeroController>();actorStates = heroCtrl.hero_state;PlayIdle();}private void Update(){UpdateAnimation();}private void UpdateAnimation(){//info = animator.GetCurrentAnimatorClipInfo(0);//currentClipLength = info[0].clip.length;//clipName = info[0].clip.name;if(actorStates == ActorStates.no_input){//TODO:}else if(actorStates == ActorStates.idle){//TODO:PlayIdle();}else if(actorStates == ActorStates.running){PlayRun();}}private void PlayRun(){animator.Play("Run");}public void PlayIdle(){animator.Play("Idle");}public void UpdateState(ActorStates newState){if(newState != actorStates){prevActorState = actorStates;actorStates = newState;}}
}


总结

最后给大伙看看效果怎么样,可以看到运行游戏后cState,hero_state和prev_hero_state都没有问题,动画也正常播放:

累死我了我去睡个觉顺便上传到github,OK大伙晚安醒来接着更新。 

相关文章:

[Unity Demo]从零开始制作空洞骑士Hollow Knight第二集:通过InControl插件实现绑定玩家输入以及制作小骑士移动空闲动画

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 前言一、通过InControl插件实现绑定玩家输入二、制作小骑士移动和空闲动画 1.制作动画2.玩家移动和翻转图像3.状态机思想实现动画切换总结 前言 好久没来CSDN看看&…...

基于鸿蒙API10的RTSP播放器(七:亮度调节功能测试)

目标&#xff1a; 当我的手指在设备左方进行上下移动的时候&#xff0c;可以进行屏幕亮度的调节&#xff0c;在调节的同时&#xff0c;有实时的调节进度条显示 步骤&#xff1a; 界面逻辑&#xff1a;使用Stack() 组件&#xff0c;完成音量图标和进度条的组合显示&#xff0c…...

基于SpringBoot+Vue的校内跑腿业务管理系统

作者&#xff1a;计算机学姐 开发技术&#xff1a;SpringBoot、SSM、Vue、MySQL、JSP、ElementUI、Python、小程序等&#xff0c;“文末源码”。 专栏推荐&#xff1a;前后端分离项目源码、SpringBoot项目源码、SSM项目源码 系统展示 【2025最新】基于JavaSpringBootVueMySQL的…...

嵌入式鸿蒙系统开发语言与开发方法分析

大家好,今天主要给大家分享一下,HarmonyOS系统的主力开发语言ArkTS语言开发方法,它是基于TypeScript(简称TS)语言扩展而来。 第一:ArkTS语言基本特性 目的:声明式UI,让开发者以更简洁,更自然的方式开发高性能应用。 声明式 UI基本特性: 基本UI描述:ArkTS定义了各种装饰…...

SpringBoot开发——整合Spring Data MongoDB

文章目录 一、MongoDB简介1、MongoDB是什么2、MongoDB 基本概念(1)文档(2)集合(3)数据库3、MongoDB的系统数据库4、MongoDB数据模型二、SpringBoot整合Spring Data MongoDB1、创建项目,添加Spring Data MongoDB依赖2、创建实体类Student3、创建StudentRepository接口4、创建…...

camouflaged object detection中的decoder最核心的作用

在 camouflaged object detection&#xff08;COD&#xff09;任务中&#xff0c;decoder 的确有一个核心作用是进行 上采样 以恢复图像的分辨率&#xff0c;但这并不是它唯一或最核心的作用。我们可以从更广泛的视角来看 decoder 的作用。 1. 上采样&#xff08;Upsampling&a…...

Java volatile

Volatile 作用&#xff1a;保证变量的可见性&#xff0c;有序性&#xff08;禁止指令重排序&#xff09;。不保证原子性。 如何保证可见性的&#xff1f; 场景&#xff1a;每个 线程 下都有一块 工作内存。要使用变量需要从 主内存 中把 变量 读取出来&#xff0c;使用完成后写…...

一条sql是如何执行的详解

一条sql是如何执行的详解 1. SQL 解析&#xff08;Parsing&#xff09; 2. 查询重写&#xff08;Query Rewrite&#xff09; 3. 查询规划&#xff08;Query Planning&#xff09; 4. 查询执行&#xff08;Query Execution&#xff09; 5. 结果返回 示例&#xff1a;查询执…...

“先天项目经理圣体”丨超适合做项目经理的4种人

总有人在问&#xff0c;什么样的人适合做项目经理&#xff0c;当项目经理需要什么样的特质&#xff1f; 你别说&#xff0c;还真有那么一些人是“先天项目经理圣体”&#xff0c;天生就是吃项目经理这碗饭的。 沟通达人丨靠“嘴”走天下 我们知道项目经理大部分的时间都在进行…...

如何从object中抽取某几个值,然后转换成数组

可以使用Object.entries(), Array.prototype.filter()和Array.prototype.map()或者解构赋值的方式从对象中抽取某些值并转换为数组 示例 1&#xff1a;使用 Object.entries(), filter() 和 map() const obj {a: 1,b: 2,c: 3,d: 4 };const keysToExtract [a, c];const extr…...

数据结构(14)——哈希表(1)

欢迎来到博主的专栏&#xff1a;数据结构 博主ID&#xff1a;代码小豪 文章目录 哈希表的思想映射方法&#xff08;哈希函数&#xff09;除留余数法 哈希表insert闭散列负载因子扩容find和erase 哈希表的思想 在以往的线性表中&#xff0c;查找速度取决于线性表是否有序&#…...

K近邻算法_分类鸢尾花数据集

import numpy as np import pandas as pd from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score1.数据预处理 iris load_iris() df pd.DataFrame(datairis.data, columnsiris.featur…...

nacos和eureka的区别详解

Nacos 和 Eureka 都是服务发现和注册中心的解决方案&#xff0c;但它们在功能、设计和使用场景上有所不同。以下是它们的详细区别&#xff1a; 1. 基本概念 Eureka&#xff1a;是由 Netflix 开发的服务发现工具。它主要用于 Java 微服务架构中的服务注册与发现。Eureka 通过 R…...

AI大模型包含哪些些技术?

Prompt Prompt提示是模型接收以生成响应或完成任务的初始文本输入。 我们给AI一组Prompt输入&#xff0c;用于指导模型生成响应以执行任务。这个输入可以是一个问题、一段描述、一组关键词&#xff0c;或任何其他形式的文本&#xff0c;用于引导模型产生特定内容的响应。 Tra…...

分布式技术概览

文章目录 分布式技术1. 分布式数据库&#xff08;Distributed Databases&#xff09;2. 分布式文件系统&#xff08;Distributed File Systems&#xff09;3. 分布式哈希表&#xff08;Distributed Hash Tables, DHTs&#xff09;4. 分布式缓存&#xff08;Distributed Caching…...

动手学习RAG: moka-ai/m3e 模型微调deepspeed与对比学习

动手学习RAG: 向量模型动手学习RAG: moka-ai/m3e 模型微调deepspeed与对比学习动手学习RAG&#xff1a;迟交互模型colbert微调实践 bge-m3 1. 环境准备 pip install transformers pip install open-retrievals注意安装时是pip install open-retrievals&#xff0c;但调用时只…...

Nacos rce-0day漏洞复现(nacos 2.3.2)

Nacos rce-0day漏洞复现&#xff08;nacos 2.3.2&#xff09; NACOS是 一个开源的服务发现、配置管理和服务治理平台&#xff0c;属于阿里巴巴的一款开源产品。影像版本:nacos2.3.2或2.4.0版本指纹&#xff1a;fofa&#xff1a;app“NACOS” 从 Github 官方介绍文档可以看出国…...

yjs04——matplotlib的使用(多个坐标图)

1.多个坐标图与一个图的折线对比 1.引入包&#xff1b;字体&#xff08;同&#xff09; import matplotlib.pyplot as plt import random plt.rcParams[font.family] [SimHei] plt.rcParams[axes.unicode_minus] False 2.创建幕布 2.1建立图层幕布 一个图&#xff1a;plt.fig…...

MOS管和三极管有什么区别?

MOS管是基于金属-氧化物-半导体结构的场效应晶体管&#xff0c;它的控制电压作用于氧化物层&#xff0c;通过调节栅极电势来控制源漏电流。MOS管是FET中的一种&#xff0c;现主要用增强型MOS管&#xff0c;分为PMOS和NMOS。 MOS管的三个极分别是G(栅极)&#xff0c;D(漏极)&…...

医院多参数空气质量监控和压差监测系统简介@卓振思众

在现代医院管理中&#xff0c;确保患者和医疗人员的健康与安全是首要任务。为实现这一目标&#xff0c;医院需要依赖高科技设施来维持最佳的环境条件。特别是&#xff0c;多参数空气质量监测系统和压差监测系统在这一方面发挥了不可替代的作用。【卓振思众】多参数空气质量监测…...

[项目实战]EOS多节点部署

文章总览&#xff1a;YuanDaiMa2048博客文章总览 EOS多节点部署 &#xff08;一&#xff09;环境设计&#xff08;二&#xff09;节点配置&#xff08;三&#xff09;区块信息同步&#xff08;四&#xff09;启动节点并验证同步EOS单节点的环境如何配置 &#xff08;一&#xf…...

setImmediate() vs setTimeout() 在 JavaScript 中的区别

setImmediate() vs setTimeout() 在 JavaScript 中的区别 在 JavaScript 中&#xff0c;setImmediate() 和 setTimeout() 都用于调度任务&#xff0c;但它们的工作方式不同。 JavaScript 的异步特性 JavaScript 以其非阻塞、异步行为而闻名&#xff0c;尤其是在 Node.js 环境…...

【Java文件操作】文件系统操作文件内容操作

文件系统操作 常见API 在Java中&#xff0c;File类是用于文件和目录路径名的抽象表示。以下是一些常见的方法&#xff1a; 构造方法&#xff1a; File(String pathname)&#xff1a;根据给定的路径创建一个File对象。File(String parent, String child)&#xff1a;根据父路径…...

关于若依flowable的安装

有个项目要使用工作流功能&#xff0c;在网上看了flowable的各种资料&#xff0c;最后选择用若依RuoYi-Vue-Flowable这个项目来迁移整合。 一、下载项目代码&#xff1a; 官方项目地址&#xff1a;https://gitee.com/shenzhanwang/Ruoyi-flowable/ 二、新建数据库&#xff…...

猜数字困难版(1-10000)

小游戏&#xff0c;通过提示每次猜高或猜低以及每次猜中的位数&#xff0c;10次内猜中1-10000的一个数。 <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><meta name"viewport" content"widthde…...

ASPICE术语表

术语来源描述活动Automotive SPICE V4.0由利益相关方或参与方执行的任务用参数Automotive SPICE V4.0应用参数是包含了在系统或软件层级可被更改的数据的软件变量&#xff0c;他们影响系统或软件的行为和属性。应用参数的概念有两种表达方式:规范(分别包括变量名称、值域范围、…...

Knife4j:打造优雅的SpringBoot API文档

1. 为什么需要API文档&#xff1f; 在现代软件开发中,API文档的重要性不言而喻。一份清晰、准确、易于理解的API文档不仅能够提高开发效率,还能降低前后端沟通成本。今天,我们要介绍的Knife4j正是这样一款强大的API文档生成工具,它专为Spring Boot项目量身打造,让API文档的生成…...

数学建模笔记—— 多目标规划

数学建模笔记—— 多目标规划 多目标规划1. 模型原理1.1 多目标规划的一般形式1.2 多目标规划的解1.3 多目标规划的求解 2. 典型例题3. matlab代码实现 多目标规划 多目标规划是数学规划的一个分支。研究多于一个的目标函数在给定区域上的最优化。又称多目标最优化。通常记为 …...

【鸿蒙HarmonyOS NEXT】页面之间相互传递参数

【鸿蒙HarmonyOS NEXT】页面之间相互传递参数 一、环境说明二、页面之间相互传参 一、环境说明 DevEco Studio 版本&#xff1a; API版本&#xff1a;以12为主 二、页面之间相互传参 说明&#xff1a; 页面间的导航可以通过页面路由router模块来实现。页面路由模块根据页…...

SonicWall SSL VPN曝出高危漏洞,可能导致防火墙崩溃

近日&#xff0c;有黑客利用 SonicWall SonicOS 防火墙设备中的一个关键安全漏洞入侵受害者的网络。 这个不当访问控制漏洞被追踪为 CVE-2024-40766&#xff0c;影响到第 5 代、第 6 代和第 7 代防火墙。SonicWall于8月22日对其进行了修补&#xff0c;并警告称其只影响防火墙的…...