Cocos2d-精灵的几个常识

本文介绍了使用Cocos2d游戏引擎时针对不同数量的精灵更新所需的性能优化策略:25个以下直接使用精灵;25至100个通过BatchNode管理;100个以上则需要进一步优化。此外还提供了碰撞检测实现方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

性能考虑

该部分是总结的cocos2d的在线文档
1)如果有每个帧有25个以下的精灵需要更新,可以直接使用精灵
class TLayer(cocos.layer.Layer):
    is_event_handler = True
    def __init__(self):
        cocos.layer.Layer.__init__(self)
        world_width, world_height = director.get_window_size()
        rand_color = [255, 0, 0]
        icolor = 0
        for i in range(qty_balls):
            ball = Ball((world_width*random.random(),
                         world_height*random.random()),
                        color=rand_color
                        )
            rand_color[icolor] = random.randint(50, 255)
            icolor = (icolor + 1)%len(rand_color)
            self.add(ball)
self.time = 0.0
self.schedule(self.update)

2)如果每个帧有25-100个以下的精灵需要更新,需要先添加到BatchNode中
class TLayer(cocos.layer.Layer):
    is_event_handler = True
        def __init__(self):
            cocos.layer.Layer.__init__(self)
            batch = cocos.batch.BatchNode()
            self.add(batch) # we add a batch to the layer ...
            world_width, world_height = director.get_window_size()
            rand_color = [255, 0, 0]
            icolor = 0
            for i in range(100):
                ball = Ball((world_width*random.random(),
                             world_height*random.random()),
                            color=rand_color
                             )
                rand_color[icolor] = random.randint(50, 255)
                icolor = (icolor + 1)%len(rand_color)
                batch.add(ball) # see ? we add sprites to the batch, not the layer
            self.batch = batch
            self.time = 0.0
            self.schedule(self.update)

3)如果有每个帧有100个以上的精灵需要更新,则需要考虑进一步优化,可以利用pyglet中所提供的API进行优化。

For a ballpark data point, a 2008 low gamming spec machine (athon 5200, radeon 4650) gives:

numballs    fps
    250     98
    500     54
    750     36

碰撞检测

如果想让Sprite有碰撞检知的功能,则必须满足两个条件

1)要类中有一个 cshape 成员

2)cshape必须是cocos.collision_model.CircleShape 或者 cocos.collision_model.AARectShape的实例

import cocos.euclid as eu
import cocos.collision_model as cm

class CollidableSprite(cocos.sprite.Sprite):
        def __init__(self, image, center_x, center_y, radius):
                super(ActorSprite, self).__init__(image)
                self.position = (center_x, center_y)
                self.cshape = cm.CircleShape(eu.Vector2(center_x, center_y), radius)

class ActorModel(object):
        def __init__(self, cx, cy, radius):
                self.cshape = cm.CircleShape(eu.Vector2(center_x, center_y), radius)

<本节完>



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值