Mr. E
Mr. E

Reputation: 75

How to update a value in corona SDK?

Why is my code not working when I check the score value? I've been trying to solve this problem for a very long time but nothing works. Why does the scoreTxt update but the if function doesn't do anything?

local function myTouchListener( event )
   if (event.phase == "began") then
      transition.pause()   
      score = score +1
      scoreTxt.text = score   
  end
 end


 local ball = display.newCircle(0,0,40)
       ball:addEventListener("touch",myTouchListener)




 if(score > 2)then
   ball.x = display.contentCenterX
   --NOTHING HAPPENS HERE
 end

Upvotes: 0

Views: 149

Answers (2)

Evan Barnes
Evan Barnes

Reputation: 56

This should solve the issue:

local score = 0
local function myTouchListener( event )
if (event.phase == "began") then
    transition.pause()   
    score = score +1
    scoreTxt.text = score   

    if(score > 2)then
        ball.x = display.contentCenterX
    end
end
end
local ball = display.newCircle(0,0,40)
ball:addEventListener("touch",myTouchListener)

The issue you are having is the if statement is happening once and score is equal to 0 or null. You need to check if score > 2 AFTER each touch occurs, not just once when the program is first run.

You also can't just make score = score + 1, because score actually equals null if you didn't initialize it. so null = null + 1 doesn't make any sense.

Upvotes: 1

Piglet
Piglet

Reputation: 28940

First of all there is no such thing as an "if function".

Assuming that the code you provided is only executed once your if statement is also only evaluated once. As score is most likely not > 2 when this happens the if statements body is not evaluated at all. That's why nothing happens.

When your code is executed you define a function myTouchListener. Then you create a circle and add the myTouchListener function as its event listener.

Then you evaluate the if-statement.

You should move that ball.x assignment to the myTouchListener to evaluate it every time score changes.

Think about it. why should the if statement be evaluated again? Who would trigger that and why?

Upvotes: 2

Related Questions