love2d 前端 联合 c++ 服务端 的 游戏开发(二)

...添加 表示背景图片的类:

-- Background.lua
Background = {} function Background:new( imgFileName, maxWidth, maxHeight ) local o = {} setmetatable( o, self) self.__index = self if imgFileName then o:SetImage( imgFileName ) end return o end function Background:SetImage( imgFileName, maxWidth, maxHeight) self.drawable = love.graphics.newImage( imgFileName ) self.scaleX = maxWidth / self.drawable:getWidth(); self.scaleY = maxHeight / self.drawable:getHeight(); end function Background:draw() love.graphics.draw( self.drawable, 0, 0, 0, self.scaleX, self.scaleY, 0, 0 ) end

创景基类:

-- scene.lua

require( "background")

Scene = {}

function Scene:new( o)
    o = o or {
        desc = nil, 
        background = nil,
        
    }
    
    setmetatable( o, self)
    self.__index = self
    
    o:_Init()
    
    return o
end

function Scene:_Init()
    self.desc = "scene"
    self.background = Background:new()
end

function Scene:Initialize()
    
end

function Scene:SetBackgroundImg( imgFileName, maxWidth, maxHeight )
    self.background:SetImage( imgFileName, maxWidth, maxHeight )
end

function Scene:SetBackground( background)
    self.background = background
end

function Scene:draw()

end

欢迎界面 的场景:

--welcone.lua

WelcomeScene = Scene:new()

function WelcomeScene:new()

    local o = {}
    setmetatable( o, self)
    self.__index = self
    
    o:Initialize()
    
    return o 
end

function WelcomeScene:Initialize()
    self:SetBackgroundImg( "img/loading.jpg", g.width, g.height )
end

function WelcomeScene:draw()
    self.background:draw()
end

主函数变更为:

require( "global")
require( "function")

function love.load()
    
    love.graphics.setMode( g.width, g.height)
    InitializeScenes()
    
    
    
    Log( "load...")
    
    g.scene = LoadScene( SCENE_WELCOME)
end

function love.draw()
    
    g.scene:draw()
end

function love.update(dt)
    
end

运行效果将如:

源代码:  http://files.cnblogs.com/Wilson-Loo/XGame.0827.zip

添加按钮操作, 使进入第二个场景:

function WelcomeScene:mousepressed(x, y, button)
    if self.btnStart:mousepressed( x, y, button) then
        g.scene = LoadScene( SCENE_1)
    end
end
-- scene_1.lua

require( "button")

Scene_1 = Scene:new()

function Scene_1:new()

    local o = {}
    setmetatable( o, self)
    self.__index = self
    
    o:Initialize()
    
    return o 
end

function Scene_1:Initialize()
    
    self:SetBackgroundImg( "img/1_1.jpg", g.width, g.height )
    
end

function Scene_1:draw()
    
    self.background:draw()

    
end

function Scene_1:update(dt)
end

function Scene:mousepressed(x, y, button)

end

至此, 完成了简单的 场景变换 和 鼠标按钮事件.

原文地址:https://www.cnblogs.com/Wilson-Loo/p/3284080.html