您的位置:首页 > 其它

love2d教程29--保存运动轨迹

2013-06-16 15:08 393 查看
感谢网友朱大仙提供的代码,才有了这篇博客。一般玩游戏的都见过魔兽,魔兽有一个功能叫做

游戏回放,可以让我们在游戏结束后分析一下自己在游戏里的不足,这篇博客便是简单的介绍如何

实现这个功能。

  不知大家注意到没有,游戏回放的记录文件都很小,这显然不是把整个游戏过程录制成视频,

而是采用记录关键信息的方式。下面先上图,操作为"q"状态切换键,"a","w","s","d"方向键,

注意快按 快放 键盘。



那么如何实现回放呢,其实关键是保存好时间和动作(当然也有其它方式)即可,只要在相同的

时间里做相同的动作,只要前提不变,就会产生相同的效果,具体的请看代码。

function love.load()
state='Ready'  --状态变量
x,y=400,300  --矩形初始坐标
move='' --移动方向控制变量
times=0 --总时间
tracks={} --记录当前按键和时间即{{按键,时间}}
doing={}  --记录当前按键
lines={}  --记录线的坐标

love.graphics.setLineWidth( 3 )

end

function love.draw()

love.graphics.setColor(255,255,255)
love.graphics.print(state.."\ntime:  "..times,50,50)
--绘制方块
love.graphics.rectangle("fill",x-15,y-15,30,30)
--绘制轨迹线条
if table.getn(lines)>=4 then
love.graphics.line(unpack(lines))
end

end

function love.update(dt)

times=times+dt
if state=="Recording" then
if table.getn(doing)~=0 then
move=doing[1]
table.insert(tracks,{doing[1],times})
table.remove(doing,1)
end
end

if state=="Playback" then
if table.getn(tracks)~=0 then
--判断时间是否与记录的时间一致
if times>=tracks[1][2] then
--把记录的运动方向赋给move
move=tracks[1][1]

--""表示按键抬起,即运动了一段,
--下面的代码把这段的线条除去了
if tracks[1][1]=="" then
table.remove(lines,1)
table.remove(lines,1)
end
table.remove(tracks,1)
end
end
end

--方块运动控制
if move=='w' then
y=y-3
elseif move=='s' then
y=y+3
elseif move=='a' then
x=x-3
elseif move=='d' then
x=x+3
end

end

function love.keypressed(key)

if state=="Recording" then
if(key=="w")or(key=="s")or(key=="a")or(key=="d")then
table.insert(doing,key)
end
if key=="q" then
state='Playback'
x,y=400,300
times=0
end
end

if(state=="Ready")and(key=="q")then
state="Recording"
times=0
table.insert(lines,x)
table.insert(lines,y)
end
end

function love.keyreleased(key)
--注意在录制状态时当按键抬起时,方块停止运动
--这时也要记录一次方块的坐标
if state=="Recording" then
if(key=="w")or(key=="s")or(key=="a")or(key=="d")then
table.insert(doing,"")
table.insert(lines,x)
table.insert(lines,y)
end
end
end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: