Lua游戏提高性能方法小结

来源:互联网 发布:java 生成自己的jar包 编辑:程序博客网 时间:2024/06/05 22:31

Lua塔防游戏提高性能方法小结

2015--02-12   何鹏

 

1.每帧刷新时,函数应尽可能高效

游戏主逻辑里,帧刷新频率一般设为60帧。该刷新函数调用频繁,如果提高其执行效率就能提升游戏性能

1. 隔帧检测:每次刷新时奇数帧继续这些函数体,如果是偶数帧,则直接返回。不影响用户体验,但这样在帧数较低时塔攻击效率可能降低。

2. 检查update函数体是否高效

例:

-----------------------------------------------------------------------------------------------------------------

local function __onUpdate()

    returnself:__update()        

end

self:scheduleUpdateWithPriorityLua(__onUpdate, 0)

function mapLayer:__update()

    --隔帧检测

    ifmath.fmod(self.frameCount,2) ~= 0 then

       self.frameCount = 0

        return

    end

   self.frameCount = self.frameCount + 1

--todo

       --函数体尽可能高效

end

-----------------------------------------------------------------------------------------------------------------

2.高效函数应尽量使用标准库函数以及简单的加减乘除运算。避免使用表结构{}

例:

-----------------------------------------------------------------------------------------------------------------

function testA()

       -- body

       localwidth = 5

       localheight = 5

       local x =100;y=100

 

       local a ={

       {['x']=x+width,['y']=y+height},

       {['x']=x+width,['y']=y-height},

       {['x']=x-width,['y']=y+height},

       {['x']=x-width,['y']=y-height}

}

end

 

function testB()

       -- body

       localwidth = 5

       localheight = 5

       local x =100;y=100

       local x1 =x+width;local x2 = x-width

       local y1 =y+height;local y2=y-height

end

 

t1 = os.clock()

for iii=1,1000000 do

    testA()

end

t2 = os.clock()

print('----xx22',t2-t1)

for iii=1,1000000 do

    testB()

end

t3 = os.clock()

print('----xx22',t3-t2)

-----------------------------------------------------------------------------------------------------------------

--result

----xx22  2.228

----xx22  0.134

 

3.粒子效果比较影响性能。影响粒子性能主要因素为粒子总数,粒子纹理,粒子的大小。在保证效果的前提下应尽可能使三个更小

 

4.怪我受击特效和buff特效应尽可能小且具有互斥关系,一个怪尽可能不频繁添加特效。当怪物遇到大量高速带BUFF塔攻击时,怪物身上可能挂了大量的特效或是频繁的删除添加特效。而有时大量特效用户也很难注意到,这不是用户关注的重点。在满足需求的前提下只挂一个特效。

例:

--判断是否已挂上相同的效果

-----------------------------------------------------------------------------------------------------------------

local tag = getTag(armatureName)

if tag then

    local arm = monster:getChildByTag(tag)

    if arm then

        return

    end

end       

armHandler = armature.create(armatureName)

monster:addChild(armHandler,C.BULLET_ZORDER,tag)

-----------------------------------------------------------------------------------------------------------------

 

5.子弹尽可能使用对象池。在塔数量很多时,屏幕可能产生大量子弹,频繁的创建删除影响性能,删除时可以先隐藏,关卡结束时集中销毁

       --从队列得到子弹

    local bullet= getElementQueue("bullet")

 

    if nil ==bullet then

        --得不到子弹了,创建

        bullet =bulletSprite:create(valueList.bulletID)

    end

   self:addChild(bullet,C.BULLET_ZORDER)

   bullet:setVisible(true)

       ......

 

6.精灵创建时应使用带纹理的创建函数,不带纹理的创建函数约慢30倍。

local sp1 =CCSprite:create("window.png")

local sp2 =CCSprite:create()

0 0