Lua function only works on first click - lua

I'm new to Lua, and I'm trying to do a simple program to change the location of an object randomly when it's clicked. The problem is, this program only works once, that is to say, upon loading the program and tapping the circle, it moves, but will not move again on subsequent taps. Any ideas?
local _W = display.contentWidth
local _H = display.contentHeight
math.randomseed(os.time())
math.random()
myCircle = display.newCircle(_W * 0.25, _H * 0.25, 50)
local function moveCircle(event)
h_random = math.random()
w_random = math.random()
display.remove(myCircle)
myCircle = display.newCircle(_W * w_random, _H * h_random, 50)
return true
end
myCircle:addEventListener("tap",moveCircle)
Many thanks in advance

I don't have any idea of what library you are using :) But try adding
myCircle:addEventListener("tap",moveCircle)
before return true in the moveCircle function.
From what I can understand from a quick inspection of the code snippet, the proposed change will bind the tap event to the newly created circle.

Related

move each individual object - lua

Im quite new to Lua so please pardon my ignorance but i cannot find the solution to my problem.
Whats going on
Im currently trying to move objects from A to B and once object is at B to restart at A and again move to B in a continuous cycle.
local function moveLeft(obj)
print("moving left")
local function resetObj(obj)
transition.to (obj,{ time = 10, x = obj.x + screenWidth + obj.width, onComplete=moveLeft })
end
transition.moveBy (obj,{ time = 3000, x = -screenWidth -obj.width, onComplete=resetObj })
end
and then called using
for idx1 = 1, 8 do
enemyRed = display.newImage("Images/enemyRed.png")
-- 7. Apply physics engine to the enemys, set density, friction, bounce and radius
physics.addBody(enemyRed, "dynamic", {density=0.1, friction=0.0, bounce=0, radius=9.5});
local xPositionEnemy = math.random() + math.random(1, screenWidth)
enemyRed.x = xPositionEnemy;
enemyRed.y = yPosition;
enemyRed.name = "enemyRed"..idx
moveLeft(enemyRed);
end
This is great and all objects are moving from A to B
Problem / issue
The issue here is that the onComplete is not called until ALL objects named "enemyRed" are at point B.
Question
What i want is for each individual object named "enemyRed" to reset to original position A once its reached its destination.
I can't answer the problem/issue because it is not clear (I added a comment). Re the question, you should probably add a A position field to each object, this way you can easily return to it (stylistic note: this is Lua, not c, you don't need semicolons). So In your loop do this:
enemyRed.x = xPositionEnemy
enemyRed.startPos = xPositionEnemy
then in your resetObj do this:
local function moveLeft(obj)
local function resetObj()
print("moving back")
transition.to (obj,
{ time = 10, x = obj.startPos, onComplete=function() moveLeft(obj) end })
end
print("moving left")
transition.moveBy (obj,
{ time = 3000, x = -screenWidth - obj.width, onComplete=resetObj })
end
The above also shows that when calling your moveLeft from the resetObj function, you have to give the obj to the moveLeft otherwise obj will be nil. The resetObjdoes not needobj` parameter since it is an upvalue already.

MapView to background - Corona SDK

I need some help with the MapView in Corona SDK. I want to put the map as background (but with all functions) and, in this case, a button to the front. Here is my code:
function scene:createScene( event )
local group = self.view
if ( system.getInfo( "environment" ) == "simulator" ) then
local simulatorMessage = "Maps not supported in Corona Simulator.\nYou must build for iOS or Android to test native.newMapView() support."
local label = display.newText( simulatorMessage, 36, 40, 270, 0, native.systemFont, 12 )
label.anchorX = 0
label.anchorY = 0
end
myMap = native.newMapView( 20, 20, display.contentWidth, display.contentHeight )
if ( myMap ) then
myMap.mapType = "normal"
myMap.x = display.contentCenterX
myMap.y = display.contentCenterY
myMap:setCenter( currentLatitude, currentLongitude )
myMap:addEventListener("mapLocation", mapLocationListener)
end
backBtn = widget.newButton
{
id="backButton",
label="Back",
fontSize="30",
labelColor={ default={1, 1, 1}, over={0, 0, 0, 0.5} },
defaultFile="images/button.png",
width = dispWidth * 0.25, height = dispHeight * 0.1,
onRelease = onBackBtnRelease
}
backBtn.anchorX = 0.5
backBtn.anchorY = 0.5
backBtn.x = display.contentWidth * 0.8
backBtn.y = dispHeight * 0.8
backBtn:toFront()
group:insert( backBtn )
group:toFront() --second try to put that button to front
end
Since the MapView is a native object I can't add it to any group and 'mapView:toBack()' doesn't work as well ('attempt to index upvalue 'myMap' (a nil value)'). In Corona SDK the button appears without the map, as expected. On device I get the map without my button, not as expected.
Is it any possible to put a native object to the back, or to force something to be in the front?
What you are trying to do with the map and the button is not currently possible with CoronaSDK.
Indeed the MapView is a native object. According to Corona's documentation, you cannot place other objects on top of a MapView.
The documentation says:
Map objects, like other native display objects, cannot be inserted into groups and are always displayed on top of regular Display Objects (groups, vector, images, and text).
See documentation here
Good luck coding.
First Check the Following :
If button doesn't appear on device most common problem will be , you might misspell the Image names(Check for Caps) or check the path of the file is proper or not.
To know in detail about the mapView : http://docs.coronalabs.com/api/library/native/newMapView.html
I know you might have visited already, its better you look again.
Thanks,

Capture Screen on Corona sdk

I tried many ways to capture the screen using corona sdk , i read
http://docs.coronalabs.com/api/library/display/captureScreen.html
Corona: how to capture a screen in corona?
However when i run the program , Corona sdk freezes and im obliged to close it
I am using Corona SDK for windows ,and sometimes I get "runtime error R6025 PURE virtual function call" , I tried lots of sample codes that have worked with others here is my code
_W = display.viewableContentWidth
_H = display.viewableContentHeight
local background = display.newRect(0, 0, 320, 480);
background:setFillColor(255,255,255);
local foo = display.newImageRect("images/foo.png",100,100);
foo.anchorX=0.5
foo.anchorY=0.5
foo.x = _W * 0.5;
foo.y = _H * 0.5;
local screenShot = display.captureScreen(true);
foo:removeSelf();
background:removeSelf();
screenShot.xScale = 0.5;
screenShot.yScale = 0.5;
screenShot.rotation = 45;
this is my build.settings file
androidPermissions =
{
"android.permission.VIBRATE",
"android.permission.WRITE_EXTERNAL_STORAGE"
},
You can also try using display.save to save the screen to a file.
Check out Lerg's code for doing that
This code will save a screenshot in the simulator when the 's' key is pressed
if app.isSimulator then
Runtime:addEventListener('key', function (event)
if event.keyName == 's' and event.phase == 'down' then
local scene = storyboard.getScene(storyboard.getCurrentSceneName())
if scene and scene.view then
display.save(scene.view, display.pixelWidth .. 'x' .. display.pixelHeight .. '_' .. math.floor(system.getTimer()) .. '.png')
return true
end
end
end)
end
You can use display.save() function to save a screenshot from given display group that passed as first argument of function

Image displays in top left corner in Corona Simulator

I just started playing with lua / Corona, and have been using the book "Create Mobile Games with Corona." (Silvia Domenech) The first project in the book is to make a simple planet defense game. For this, I am using a multi-screen application (or "scene" as it's called in OS X). The very first step is displaying an image using groups in Corona.
The book has me enter the following code in the main scene group:
local image = display.newImage( "images/iphone_767.png")
group:insert( image )
After adding it to (what I think is) the correct group, the code looks like this:
-- Called when the scene's view does not exist:
function scene:createScene( event )
local group = self.view
-----------------------------------------------------------------------------
local image = display.newImage( "images/iphone_767.png")
group:insert( image )
-- CREATE display objects and add them to 'group' here.
-- Example use-case: Restore 'group' from previously saved state.
-----------------------------------------------------------------------------
end
For the image, I first tried an image that was 320 x 480. When it rendered on the simulator, it is situated way off to the top left of the simulator. Here is a screenshot of how it renders: http://imgur.com/Kpm0XTd
The config file is set for 320 x 480 px. I'm really at a loss as to what could be causing this since I haven't modified anything outside of what I described. Any ideas?
Set the x and y values of the token to screen center (assuming you want to center it):
image.x = display.contentWidth/2
image.y = display.contentHeight/2
Thanks
Anand
I personally like setting a variable to display.contentWidth and display.contentWidth.
_W = display.contentWidth
_H = display.contentHeight
image.x = _W/2
image.y = _H/2
You could also format it like so:
image.x = _W*.5
image.y = _W*.5
Corona SDK has recently started using a new graphics engine that affects how things are positioned. The display.newImage() used to draw the top left corner at 0, 0, but now it draws the center at 0, 0. Your best bet is to always explicitly set the .x and .y of the image where you want it.
Seems there is simplified way exists now:
image.x = display.contentCenterX
image.y = display.contentCenterY
Or single line:
local image = display.newImage('images/iphone_767.png', display.contentCenterX, display.contentCenterY)
But now it is seems more conventional pattern is to create centeredGroup first:
-- Create centered group
local centeredGroup = display.newGroup()
centeredGroup.x = display.contentCenterX
centeredGroup.y = display.contentCenterY
-- Add background
local image = display.newImage(centeredGroup, 'images/iphone_767.png', display.contentCenterX, display.contentCenterY)

Gideros GTween Event Listener

I'm trying a GTween example from the following link
Gideros GTween with Easing
The example doesn't work out of the box, so I dug into the source code of GTween and added the following lines to my example in order to allow event dispatching.
local tween = GTween.new(jewel, 2, animProperties, gtweenProperties)
tween.suppressEvents = false -- New Line #1
tween.dispatchEvents = true -- New Line #2
tween:addEventListener('complete', function()
stage:removeChild(jewel)
jewel = nil
end)
However, the app crashes. I tried commenting the following line in gtween.lua
self:dispatchEvent(Event.new(name))
and the app doesn't crash, however the callbacks aren't invoked (obviously, why would it?)
This is the stack trace from the app.
gtween.lua:445: attempt to call method 'dispatchEvent' (a boolean value)
stack traceback:
gtween.lua:445: in function 'dispatchEvt'
gtween.lua:255: in function 'setPosition'
gtween.lua:86: in function <gtween.lua:74>
Any pointers would be greatly appreciated. Thanks.
PS: I'm not sure if this is a bug on Gideros.
i just tried with the latest gideros' gtween (note that it is edited 10 days ago), and use this sample (i took the sample from your link and add sprite definition, also include a image file in project) and it works(the callback is called) :
local animate = {}
animate.y = 100
animate.x = 100
animate.alpha = 0.5
animate.scaleX = 0.5
animate.scaleY = 0.5
animate.rotation = math.random(0, 360)
local properties = {}
properties.delay = 0
properties.ease = easing.inElastic
properties.dispatchEvents = true
local sprite = Bitmap.new(Texture.new("box.png")) -- ADD THIS
stage:addChild(sprite) -- ADD THIS
local tween = GTween.new(sprite, 10, animate, properties)
tween:addEventListener("complete", function()
stage:removeChild(sprite)
sprite = nil
end)

Resources