I am having trouble using modules to add a background and a player.
I have two files, level01.lua (contains background and level info) and gamefunctions.lua (contains the player related functions)
Basically, what I am doing is, I added the player and background into a group called bgGroup in level01.lua.
Then, based on the player’s x position, either I move the player or move bgGroup and the player together (running in opposite direction in same speed to make the player seem not moving).
Problem is, bgGroup is returning nil on line 9 of gamefunctions.lua.
It was working fine when all this was in one file but now I am trying to break it apart into smaller modules.
Am I going the wrong way in doing this?
In case, you ask why I am using velocity instead of manipulating x position, that’s because it gives me a better result in jumping (using x position, if I let go of the directional button while jumping, it stops the character from moving horizontally mid air, whereas using velocity, the player keeps moving horizontally until it lands then stops).
level01.lua
local gamefunctions = require("gamefunctions")
-- groups
local bgGroup = display.newGroup()
-- create objects
local player = gamefunctions.newPlayer(\_W \* 0.1, \_H \* 0.5)
-- objects
local bg\_img = display.newImageRect("bg.jpg", 960, 320)
bg\_img:setReferencePoint(display.TopLeftReferencePoint)
bg\_img.x = 0; bg\_img.y = 0
bgGroup:insert(bg\_img)
bgGroup:insert(player)
gamefunctions.lua
[code]
– created a player object
– actions
local function movePlayerRight(e)
vx, vy = player:getLinearVelocity()
if playerRight then
if player.x < _W * 0.5 then
player:setLinearVelocity(playerSpeedRight, vy )
elseif bgGroup.x <= -_W then
player:setLinearVelocity(playerSpeedRight, vy)
else
bgGroup.x = bgGroup.x - playerSpeedRight / 66
player:setLinearVelocity(playerSpeedRight, vy)
end
end
end
local function movePlayerLeft(e)
vx, vy = player:getLinearVelocity()
if playerLeft then
if player.x > (_W * 2) - _W * 0.5 then
player:setLinearVelocity(playerSpeedLeft, vy)
elseif bgGroup.x >= 0 then
player:setLinearVelocity(playerSpeedLeft, vy)
else
bgGroup.x = bgGroup.x - playerSpeedLeft / 66
player:setLinearVelocity(playerSpeedLeft, vy)
end
end
end
[/code] [import]uid: 39031 topic_id: 15421 reply_id: 315421[/import]