lua - How to stop an object from moving past a point -
i wondering if there way stop object moving off screen. in code, have controllable character (player) , want prevent moving left when it's x coordinate < 1
i have tried in code below, however, player not stopped if hold down left arrow key.
is there way fix this? if had guess, somehow need program continuously check case player.x < 1
motionx = 0; -- variable used move character along x axis speed = 10; -- set walking speed local function moveplayer (event) player.x = player.x + motionx; end runtime:addeventlistener("enterframe", moveplayer) local function onkeyevent( event ) if ( event.phase == "down" ) if ( event.keyname == "left" ) , player.x > 1 motionx = -speed return true elseif ( event.keyname == "right" ) motionx = speed return true end end end runtime:addeventlistener( "key", onkeyevent )
you need check boundaries , set motionx zero:
local player = display.newcircle(display.contentcenterx, display.contentcentery, 10) local motionx = 0; -- variable used move character along x axis local speed = 10; -- set walking speed local function moveplayer( event ) player.x = player.x + motionx; if player.x < 0 player.x = 0 motionx = 0 elseif player.x > display.contentwidth player.x = display.contentwidth motionx = 0 end end runtime:addeventlistener( "enterframe", moveplayer ) local function onkeyevent( event ) if event.phase == "down" if event.keyname == "left" motionx = -speed return true elseif event.keyname == "right" motionx = speed return true end end end runtime:addeventlistener( "key", onkeyevent )
Comments
Post a Comment