Detailed description of lua implementation inheritance in cocos2dx

Source: Internet
Author: User
Environment: The cocos2dx version is 2.1.4. Target: players and monsters are usually in the game. They all have the same action status, such as idle, walk, attack, and defense, we need to abstract some of the same methods in player and monster code implementation: cocos2dx actually provides a tool function for class inheritance, samplesLua In sdk

Environment: The cocos2dx version is 2.1.4. Target: players and monsters are usually in the game. They all have the same action status, such as idle, walk, attack, and defense, we need to abstract some of the same methods in player and monster code implementation: cocos2dx actually provides a tool function for class inheritance, samples/Lua In sdk

Environment:

Cocos2dx version 2.1.4


Objectives:

There are usually players and monsters in the game. They all have the same action status, such as idle, walk, attack, defense, etc, we need to abstract the same part of the player and monster code implementation.


Method:

Cocos2dx actually provides a tool function for class inheritance. In the sdk samples/Lua/TestLua/Resources/luasloud directory, there is a file named "extern. lua ", which has the following code:

--Create an class.function class(classname, super)    local superType = type(super)    local cls     if superType ~= "function" and superType ~= "table" then        superType = nil        super = nil    end     if superType == "function" or (super and super.__ctype == 1) then        -- inherited from native C++ Object        cls = {}         if superType == "table" then            -- copy fields from super            for k,v in pairs(super) do cls[k] = v end            cls.__create = super.__create            cls.super    = super        else            cls.__create = super        end         cls.ctor    = function() end        cls.__cname = classname        cls.__ctype = 1         function cls.new(...)            local instance = cls.__create(...)            -- copy fields from class to native object            for k,v in pairs(cls) do instance[k] = v end            instance.class = cls            instance:ctor(...)            return instance        end     else        -- inherited from Lua Object        if super then            cls = clone(super)            cls.super = super        else            cls = {ctor = function() end}        end         cls.__cname = classname        cls.__ctype = 2 -- lua        cls.__index = cls         function cls.new(...)            local instance = setmetatable({}, cls)            instance.class = cls            instance:ctor(...)            return instance        end    end     return clsend

The first parameter of the function class is the name of the class we want to implement. You can pass a function or table to the second parameter without passing the second parameter.


We inherit from CCSprite in cocos2dx and play different animations in different States.


Implementation:

The basic categories of players and monsters can be implemented as follows:

Require "extern" Actor = class ("Actor", function () return CCSprite: create () end) Actor. _ index = Actor -- constant kActorStateUnkown = 0 kActorStateIdle = 1 kActorStateAttack = 2 kActorStateDefense = 3 kActorStateWalk = 4 -- attribute Actor. _ state = kActorStateUnkownActor. _ idle_action = nilActor. _ attack_action = nilActor. _ defense_action = nilActor. _ Role _action = nil -- Method function Actor: idle () if self. _ state ~ = KActorStateIdle then self: stopAllActions () pcall (self: runAction (self. _ idle_action) self. _ state = kActorStateIdle endendendfunction Actor: attack () if self. _ state ~ = KActorStateAttack then self: stopAllActions () pcall (self: runAction (self. _ attack_action) self. _ state = kActorStateAttack endendfunction Actor: defense () if self. _ state ~ = KActorStateDefense then self: stopAllActions () pcall (self: runAction (self. _ defense_action) self. _ state = kActorStateDefense endendfunction Actor: walk () if self. _ state ~ = KActorStateWalk then self: stopAllActions () pcall (self: runAction (self. _ required _action) self. _ state = kActorStateWalk endendfunction Actor: create () local actor = Actor. new () return actorend

With the base class, the player's implementation can be as follows:


1. gamer data Singleton

require "extern"PlayerData = class("PlayerData")PlayerData.__index = PlayerDataPlayerData._inited = 0PlayerData._idle_action = nilPlayerData._attack_action = nilPlayerData._defense_action = nilPlayerData._walk_action = nilfunction PlayerData:lazyInit()  if (self._inited ~= 0) then    return  end  local cache = CCSpriteFrameCache:sharedSpriteFrameCache()  cache:addSpriteFramesWithFile("pd_sprites.plist")  local frames = nil  local frame = nil  local anim = nil  -- idle  frames = CCArray:createWithCapacity(6)  for i = 0, 5 do    frame = cache:spriteFrameByName(        string.format("hero_idle_%02d.png", i))    frames:addObject(frame)  end  anim = CCAnimation:createWithSpriteFrames(frames, 1.0 / 12.0)   self._idle_action = CCRepeatForever:create(CCAnimate:create(anim))  -- attack  frames = CCArray:createWithCapacity(3)  for i = 0, 2 do    frame = cache:spriteFrameByName(        string.format("hero_attack_00_%02d.png", i))    frames:addObject(frame)  end  anim = CCAnimation:createWithSpriteFrames(frames, 1.0 / 12.0)   self._attack_action = CCRepeatForever:create(CCAnimate:create(anim))  -- defense  self._defense_action = self._idle_action  -- walk  frames = CCArray:createWithCapacity(8)  for i = 0, 7 do    frame = cache:spriteFrameByName(        string.format("hero_walk_%02d.png", i))    frames:addObject(frame)  end  anim = CCAnimation:createWithSpriteFrames(frames, 1.0 / 12.0)   self._walk_action = CCRepeatForever:create(CCAnimate:create(anim))  self._inited = 1endfunction PlayerData:getAllAction()  self:lazyInit()  return self._idle_action, self._attack_action, self._defense_action,    self._walk_actionend


2. Players

require "actor"require "playerdata"Player = class("Player", function()    return Actor:create()end)Player.__index = Playerfunction Player:init()  self._idle_action, self._attack_action, self._defense_action,    self._walk_action = PlayerData:getAllAction()endfunction Player:create()  local player = Player.new()  player:init()  return playerend

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.