跳转到内容

第一个游戏案例

相关代码

--使用前记得替换为自己地图中的实例ID哦~
local GameClient = {
Time = 0 --当前时间
}
--定义道具类型
local prop_Id=1106022000000000--尖叫鸭
--信号触发盒实例ID,用于作为触发机关
local box_trigger=233
--生物实例ID,作为怪物模板
local monster_id=234
--定时器触发间隔(单位:秒)
local delay_time=2
--特效类型ID
local effect_type_id=137
--控件实例ID,用于做计分器
local ui_socre=100046
--用于记录分数
local socre=0
-- 客户端游戏开始时
function GameClient:OnStart()
printLog("[GameClient:OnStart]")
self.Time = TimerManager:GetTimeSeconds()
-- 注册网络协议
System:BindNotify(NetMsg.SeverLog, self.OnSeverLog, self)
--获取本地玩家
local player_Id=Character:GetLocalPlayerId()
--给玩家添加道具
Character:AddProp(player_Id,prop_Id)
--备注:如果对API的使用存在疑惑,可以将鼠标悬浮在API上查看提示,也可以查询API手册,我们为每个API都提供了用例。
--注册监听事件
System:RegisterEvent(
--事件类型:当角色进入信号触发盒
Events.ON_CHARACTER_ENTER_SIGNAL_BOX,
--事件回调函数
function (playerId, signalBoxId) --playerId = 玩家id, signalBoxId = 信号触发盒id
--在这里编写事件逻辑
printLog("ON_CHARACTER_ENTER_SIGNAL_BOX", playerId, signalBoxId)
if signalBoxId== box_trigger then
--复制场景中的生物,创建一个生物
--保存新创建的怪物实例ID
local monster=Creature:SpawnCreatureBySceneID(monster_id, Engine.Vector(0, 0, 100), Engine.Vector(0, 0, 0))
--让怪物跟随玩家
Creature:CreatureSwitchBehaviorToFollowPlayer(monster, player_Id, 9999, 5, 20)
end
--事件逻辑结束
end)
--添加一个循环触发定时器
TimerManager:AddLoopTimer(delay_time,
function()
--在这里编写定时器逻辑
--给玩家添加道具
Character:AddProp(player_Id,prop_Id)
--定时器逻辑结束
end,delay_time)
--注册监听事件
System:RegisterEvent(
--事件类型:当生物受到伤害前
Events.ON_BEFORE_CREATURE_TAKING_DAMAGE,
--事件回调函数
function (creatureId, killer, damage) -- creatureId = 生物ID, killer = 发出伤害的ID, damage = 伤害的数值
--在这里编写事件逻辑
--获取怪物位置
local pos = Creature:GetPosition(creatureId)
--特效的大小
local effect_size=0.3
--在怪物的位置播放特效
local effectId = Particle:PlayAtPosition(effect_type_id, pos, effect_size, true, 1)
--事件逻辑结束
printLog("打中怪物了!")
--分数加1
socre = socre + 1
--拼接显示的文字
local socre_string='当前分数为'..tostring(socre)
--同步修改UI
UI:SetText({ui_socre},socre_string)
--打印到控制台
printLog(socre_string)
end)
end
-- 游戏更新
function GameClient:OnUpdate()
local currentTime = TimerManager:GetTimeSeconds()
local delta = currentTime - self.Time -- 与上一次更新时的时间间隔,单位是秒
self.Time = currentTime
--每10秒给服务器发送一次请求a
local lastSentTime = self.lastSentTime or 0 --上一次发送消息的时间
if lastSentTime > 10 then
self.lastSentTime = 0
local count = self.lastSentCount or 1
self.lastSentCount = count + 1
local msg = {
text = "你好, 我是客户端!",
count = count,
}
System:SendToServer(NetMsg.ClientReq, msg)
else
self.lastSentTime = lastSentTime + delta
end
end
return GameClient