Home Database Mysql Tutorial cocos2dx中lua实现继承详解

cocos2dx中lua实现继承详解

Jun 07, 2016 pm 03:37 PM
lua accomplish environment inherit Detailed explanation

环境: cocos2dx版本为2.1.4 目标: 游戏中一般有玩家和怪物,他们都有相同的动作状态,如:idle、walk、attack、defense等,我们需要抽象出玩家和怪物的代码实现中中相同的部分 方法: cocos2dx中其实已经提供了类继承的一下工具函数,在sdk中的samples/Lua

环境:

cocos2dx版本为2.1.4


目标:

游戏中一般有玩家和怪物,他们都有相同的动作状态,如:idle、walk、attack、defense等,我们需要抽象出玩家和怪物的代码实现中中相同的部分


方法:

cocos2dx中其实已经提供了类继承的一下工具函数,在sdk中的samples/Lua/TestLua/Resources/luaScript目录下有一个名为“extern.lua”,其中有段代码如下:

--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 cls
end
Copy after login

函数class的第一个参数就是我们要实现的类的名称,可以不传第二个参数或者给第二参数传一个function或者table。


我们从cocos2dx中的CCSprite继承,根据不同的状态播放不同的动画


实现:

玩家和怪物的基类可如下实现:

require "extern"

Actor = class("Actor", function()
    return CCSprite:create()
end)

Actor.__index = Actor

-- 常量
kActorStateUnkown = 0
kActorStateIdle = 1
kActorStateAttack = 2
kActorStateDefense = 3
kActorStateWalk = 4

-- 属性
Actor._state = kActorStateUnkown
Actor._idle_action = nil
Actor._attack_action = nil
Actor._defense_action = nil
Actor._walk_action = nil

-- 方法
function Actor:idle()
  if self._state ~= kActorStateIdle then
    self:stopAllActions()
    pcall(self:runAction(self._idle_action))
    self._state = kActorStateIdle
  end
end

function Actor:attack()
  if self._state ~= kActorStateAttack then
    self:stopAllActions()
    pcall(self:runAction(self._attack_action))
    self._state = kActorStateAttack
  end
end

function Actor:defense()
  if self._state ~= kActorStateDefense then
    self:stopAllActions()
    pcall(self:runAction(self._defense_action))
    self._state = kActorStateDefense
  end
end

function Actor:walk()
  if self._state ~= kActorStateWalk then
    self:stopAllActions()
    pcall(self:runAction(self._walk_action))
    self._state = kActorStateWalk
  end
end

function Actor:create()
  local actor = Actor.new()
  return actor
end
Copy after login

有了基类后,玩家的的实现可以如下:


1、玩家的数据单例

require "extern"

PlayerData = class("PlayerData")

PlayerData.__index = PlayerData

PlayerData._inited = 0
PlayerData._idle_action = nil
PlayerData._attack_action = nil
PlayerData._defense_action = nil
PlayerData._walk_action = nil

function 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 = 1
end

function PlayerData:getAllAction()
  self:lazyInit()
  return self._idle_action, self._attack_action, self._defense_action,
    self._walk_action
end
Copy after login


 2、玩家类

require "actor"
require "playerdata"

Player = class("Player", function()
    return Actor:create()
end)

Player.__index = Player

function Player:init()
  self._idle_action, self._attack_action, self._defense_action,
    self._walk_action = PlayerData:getAllAction()
end

function Player:create()
  local player = Player.new()
  player:init()
  return player
end
Copy after login


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1665
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
How to implement dual WeChat login on Huawei mobile phones? How to implement dual WeChat login on Huawei mobile phones? Mar 24, 2024 am 11:27 AM

How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

Detailed explanation of C++ function inheritance: How to use 'base class pointer' and 'derived class pointer' in inheritance? Detailed explanation of C++ function inheritance: How to use 'base class pointer' and 'derived class pointer' in inheritance? May 01, 2024 pm 10:27 PM

In function inheritance, use "base class pointer" and "derived class pointer" to understand the inheritance mechanism: when the base class pointer points to the derived class object, upward transformation is performed and only the base class members are accessed. When a derived class pointer points to a base class object, a downward cast is performed (unsafe) and must be used with caution.

Detailed explanation of obtaining administrator rights in Win11 Detailed explanation of obtaining administrator rights in Win11 Mar 08, 2024 pm 03:06 PM

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

PHP Programming Guide: Methods to Implement Fibonacci Sequence PHP Programming Guide: Methods to Implement Fibonacci Sequence Mar 20, 2024 pm 04:54 PM

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence

Detailed explanation of division operation in Oracle SQL Detailed explanation of division operation in Oracle SQL Mar 10, 2024 am 09:51 AM

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

How to implement the WeChat clone function on Huawei mobile phones How to implement the WeChat clone function on Huawei mobile phones Mar 24, 2024 pm 06:03 PM

How to implement the WeChat clone function on Huawei mobile phones With the popularity of social software and people's increasing emphasis on privacy and security, the WeChat clone function has gradually become the focus of people's attention. The WeChat clone function can help users log in to multiple WeChat accounts on the same mobile phone at the same time, making it easier to manage and use. It is not difficult to implement the WeChat clone function on Huawei mobile phones. You only need to follow the following steps. Step 1: Make sure that the mobile phone system version and WeChat version meet the requirements. First, make sure that your Huawei mobile phone system version has been updated to the latest version, as well as the WeChat App.

Master how Golang enables game development possibilities Master how Golang enables game development possibilities Mar 16, 2024 pm 12:57 PM

In today's software development field, Golang (Go language), as an efficient, concise and highly concurrency programming language, is increasingly favored by developers. Its rich standard library and efficient concurrency features make it a high-profile choice in the field of game development. This article will explore how to use Golang for game development and demonstrate its powerful possibilities through specific code examples. 1. Golang’s advantages in game development. As a statically typed language, Golang is used in building large-scale game systems.

PHP Game Requirements Implementation Guide PHP Game Requirements Implementation Guide Mar 11, 2024 am 08:45 AM

PHP Game Requirements Implementation Guide With the popularity and development of the Internet, the web game market is becoming more and more popular. Many developers hope to use the PHP language to develop their own web games, and implementing game requirements is a key step. This article will introduce how to use PHP language to implement common game requirements and provide specific code examples. 1. Create game characters In web games, game characters are a very important element. We need to define the attributes of the game character, such as name, level, experience value, etc., and provide methods to operate these

See all articles