# Moving sprite with touch

Ok so I want to move my sprite by touch along the x axis so I’ve already figured out how to do that. However I want the player to only be able to move the sprite in a limited area. Here’s the draw function I tried using :

``````
function setup()
end

-- This function gets called once every frame
function draw()

background(70, 116, 31, 255)

if CurrentTouch.x > 310 and CurrentTouch.x < 725 then
sprite(theSprite,CurrentTouch.x, 500)
end
end

``````

This however makes the sprite disappear when it goes off the edge of the area I want the sprite to be limited to. I would like the sprite to remain on the screen of the user clicks outside of the designated area, on the edge or wherever the user last touched that was in the right space. Thanks

Try this, instead of the if statement:

``````sprite(theSprite, math.max(310, math.min(725, CurrentTouch.x)), 500)
``````

math.max(a, b) returns the largest number, either a or b, and math.min(a, b) does the opposite, the smaller number of the two. You can use this to “clamp” a number to a certain range.

@RedCoder1 Here’s an example of moving a sprite but limiting it’s movement to the screen.
Also, when you post code, put 3 ~ before and after your code so it’s formatted correctly. I added the 3 ~ before and after your code.

``````
displayMode(FULLSCREEN)

function setup()
tx=WIDTH/2
ty=HEIGHT/2
end

function draw()
background(70, 116, 31, 255)
sprite(theSprite,tx,ty)
end

function touched(t)
if t.state==MOVING then
tx=tx+t.deltaX
if tx<80 then
tx=80
end
if tx>WIDTH-80 then
tx=WIDTH-80
end
ty=ty+t.deltaY
if ty<80 then
ty=80
end
if ty>HEIGHT-80 then
ty=HEIGHT-80
end
end
end

``````

That’s exactly what I was looking for, thank you very much.