如何在 Corona SDK 中更新值?

为什么我在检查分数值时代码不工作?我已经尝试解决这个问题很长时间了,但什么都不起作用。为什么 scoreTxt 更新了但 if 函数没有做任何事情?

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
点赞
用户2858170
用户2858170

首先,并没有“if函数”的存在。

假设您提供的代码只执行一次,则if语句也只被评估一次。由于在发生这种情况时得分很可能不大于2,因此if语句的主体根本没有被评估。这就是为什么什么都没有发生的原因。

当执行代码时,您定义了一个名为myTouchListener的函数。然后,您创建一个圆,并将myTouchListener函数添加为其事件侦听器。

然后,您评估if语句。

您应该将该ball.x赋值移至myTouchListener中,以便在每次分数变化时对其进行评估。

想一想。为什么if语句应该再次被评估?谁会触发它,为什么?

2017-06-29 12:05:02
用户4261637
用户4261637

这应该解决问题:

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)

你遇到的问题是 if 语句只执行一次,此时 score 等于 0 或 null。你需要在每次触摸事件发生后检查 score 是否大于 2,而不仅仅是在程序首次运行时。

你也不能只是让 score = score + 1,因为如果你没有初始化 score,那么 score 实际上就等于 null。因此,null = null + 1 没有任何意义。

2017-06-29 18:49:11