昨天在深圳和同事聚了聚 聊了聊前公司也是百感交集 也许确实是位置不一样所以看东西的角度和在乎的东西不一样吧
也许有一天自己也能站在这个高度会有不一样的体会
废话不多说 其实状态机用C#比较好写 lua主要是实现继承太蛋疼了 不过很多游戏都要求热更 总有要求全部用lua实现的例子
我也是去github上参考了下源码 确实对已经有工作经验的人来说 直接去看源码是成长最快的方式 以前是太执着看视频了 总想能直接起手就写出和教课的一样特别好看的框架和代码 浪费了太多时间 要是省事的话就直接copy这个吧 直接代码
首先是状态机脚本
首先调一个class脚本方便lua继承和重载
StateMachine = class("StateMachine")
function StateMachine:ctor()
-- print("StateMachine===================ctor")
self.currentState = nil
end
function StateMachine:ChangeState(state)
if state == nil then
print("状态机状态不能为空")
return false
end
-- print("当前状态机的名字", state.name)
-- 退出前一个状态
if self.currentState ~= nil then
self.currentState:OnExit()
end
self.currentState = state
-- 为状态设置状态机
self.currentState:SetStateMachine(self)
self.currentState:OnEnter()
return true
end
-- 状态机更新
function StateMachine:OnStay()
-- print("StateMachine===========OnStay")
if self.currentState ~= nil then
-- print("StateMachine:OnExecute state:"..self.currentState.name )
self.currentState:OnStay()
end
end
-- 获取当前状态
function StateMachine:GetCurrentState()
return self.currentState
end
其他逻辑大同小异 然后是状态基类并绑定上状态机
State = class("State")
function State:ctor(name)
-- print("State==============ctor")
self.name = name
end
-- [Comment]
-- 绑定状态机
function State:SetStateMachine(machine)
self.machine = machine
end
function State:OnEnter()
end
function State:OnStay()
end
function State:OnExit()
end
然后就是各种派生类的建立 举个idle的例子
StateIdle = class("StateIdle", State)
function StateIdle:OnEnter()
print("StateIdle=============OnEnter")
self.machine.mJoy.isRun=true
self.machine.mAnimator:SetBool(StateTransitionName[StateTransitionIndex.IDLE], true)
end
function StateIdle:OnStay()
if self.machine.mAnimatorStateInfo:IsName("idle") then
self.machine.mAnimator:SetInteger(TRANSITION_CURRSTATE, StateTransitionIndex.IDLE)
end
end
function StateIdle:OnExit()
end
这里状态机我是参考的悠游课堂的方式啊 我感觉比较对我口味 两个变量控制各自的状态切换 然后具体状态逻辑再单独写一个ai 不和状态机混在一起
结构大概是这样 然后在manager脚本上直接new一个machine
直接写方法测试
这样一个简单的lua状态机框架就搭好了 后面如果有不同的普攻动画 不同的技能动画 可以再往里面拓展 相对来说我感觉应该是目前比较满意的一个方式 后面如果有遇到什么问题再补充
说个题外话:今天大佬建议我想把3D数学学好,这个是做游戏的基础,书刚买,想想自己游戏行业一年多的时间,真真完全看完一本书好像也就是一本大话设计模式,说来惭愧,躺在抽屉里很久的乐乐shader丛书真的是抱歉了,趁着现在还有点业余时间,从这个本3D数学开始吧,打算花半个月到一个月时间看完全本书,游戏开发确实不是件容易的活,但是能做自己喜欢的职业,相对来说还是不错的,你说呢,今天就到这,下个博客见。