CocosNodes Examples

Parent-Child examples

Building a scene, object instantiation omitted

# a scene with 2 layers; the background would be seen behind the game layer because of z values
scene.add( background_layer, z=0 )
scene.add( game_layer, z=1 )

# the layer with 1 bloody pacman sprite
blody_pacman_sprite.position = (100, 100)
game_layer.add( bloody_pacman_sprite )

# the bloody pacman has two daggers !!!
sprite.add( dagger_far_sprite, z=-1 )
sprite.add( dagger_near_sprite, z=1  )
# the draw order is dagger_far, bloody_pacman, dagger_near

# also they are zombie alien cowboys in the game,
# so we add a bunch of them to the game_layer
...

A dagger has touched a zombie alien cowboy so it wants to spawn a nasty blotch of green blood. We could add the blotch_sprite to the zac_sprite, an then the blotch will follow the zombie:

zac_zprite.add(blotch_sprite, z = 1)

or we could add to the game_layer, and the blotch will not follow the zombie:

layer = zac_sprite.parent # should be game_layer, because our staggering
layer.add(blotch_sprite)

If for some ridiculous reason a dagger needs to grab a reference to the game_layer we could use 'get_ancestor'. Due to to way we staged the scene, we know game_layer is parent of bloody_pacman_sprite which is parent of the dagger. So:

layer = dagger_near.get_ancestor(Layer)

should produce game_layer.

A zombie is killed, we can retire from the scene with:

zac_sprite.kill()

or with:

game_layer.remove(zac_sprite)

or if we named it "T'chkss" when we added to the game_layer, like in:

game_layer.add(zac_sprite, name = "T'chkss", z=4)

then we can retire it with:

game_layer.remove("T'chkss")

Note that in current cocos if you add with name then you should remove by name, else the name will become unusable for new additions.

Spatial Placement snippets

Example:

# place the sprite in 320,240
sprite.position = (320,240)

or by using actions. Example:

# move the sprite to 320,240 in 5 seconds
sprite.do( MoveTo( (320,240, duration=2 ) )

Automated changes along the time snippets

You can modify attributes to any CocosNode object. By example:

scene.do( ScaleTo(2, duration=2) )

layer.do( RotateBy(360, duration=3) )

sprite.do( Blink(5, duration=1 ) )

label.do( JumpBy( (100,100), 50, 5, duration=3) )