Corona SDK Lua游戏触摸功能无报错却失效,请求协助排查
Hey there! Let's figure out why your touch functionality isn't working—no errors can be tricky, but I spotted a couple of key issues in your code that are causing the problem. Here's what's wrong and how to fix it:
1. Typo in Function Name
You defined your jet force function as acivateJets (missing a 't'), but in your touch handler you're trying to assign activateJets to jet.enterFrame. Since Lua can't find the function with the correct name, the logic never runs. Fix the function name to match everywhere.
2. Incorrect Method Call for applyForce
In Lua, when calling a method on an object (like your jet physics body), you need to use the colon : instead of a dot .. The colon automatically passes the self parameter, which is required for applyForce to work correctly.
3. Missing Cleanup on Touch End
Right now, once you start the enterFrame listener on touch begin, it never stops—your jet will keep accelerating upward even after you release the screen. You need to remove the listener when the touch ends.
Fixed Full Code
local physics = require "physics" physics.start() -- jet local jet = display.newImage("redJet.png") jet.x = 100 jet.y = 100 physics.addBody(jet, "dynamic", {density=.1, bounce=0.1, friction=.2, radius=12}) function activateJets(self, event) -- Use colon to call applyForce with self self:applyForce(0, -1.5, self.x, self.y) end function touchScreen(event) if event.phase == "began" then jet.enterFrame = activateJets Runtime:addEventListener("enterFrame", jet) end if event.phase == "ended" then -- Remove the enterFrame listener when touch ends Runtime:removeEventListener("enterFrame", jet) jet.enterFrame = nil end end Runtime:addEventListener("touch", touchScreen)
Give this adjusted code a try—your touch controls should now work as expected, with the jet accelerating when you hold the screen and stopping when you release it.
内容的提问来源于stack exchange,提问作者Mukesh

