Make a sprite move when touched?

Here is my code and I am trying to make it so I touch the sprite the sprite will go up and randomly to the left or right. Here is my code any help appreciated!

supportedOrientations(LANDSCAPE_ANY)

function setup()
    p1=physics.body(CIRCLE,10)
    p1.x=10
    p1.y=10
    p1.gravityScale=0
end

function draw()
    background(255, 255, 255, 0)
    fill(255,0,0)
    sprite("Documents:football",p1.x,p1.y)
    if p1.y<=10 then
        p1.gravityScale=0
        p1.linearVelocity=vec2(0,0)
    end
end

function touched(t)
    if t.state==BEGAN then
        p1.linearVelocity=vec2(100,600)
        p1.gravityScale=1
        p1.x=10
        p1.y=10
    end
end

You don’t need to use physics function for that. Just a simple tween will do it. Check this out:


function setup()
   object = vec2(300,300)
end

function draw()
    background()
    
    sprite("Planet Cute:Rock",object.x, object.y) 
    
end

function touched(t)
    
    if t.state == BEGAN then 
     tween(1,object,{x=math.random(50,WIDTH-50),y=math.random(50,HEIGHT-50)})
    end
        
 end
        

Thanks for the code but how do I make it so when I touch the sprite not the screen it moves?

You need to add two more conditions to the if statement for that. Like this:




function setup()
    object = vec2(300,300)
end

function draw()
    background()
    
    sprite("Planet Cute:Rock",object.x, object.y) 
    
end

function touched(t)
    
    if t.state == BEGAN 
       and math.abs(t.x-object.x)<=50 
       and math.abs(t.y-object.y)<=50 then 
     tween(1,object,{x=math.random(50,WIDTH-50),y=math.random(50,HEIGHT-50)})
    end
        
end
        

        

Thanks for the code but how could I get is to work with gravity?

We need to use physics then. I modified your code a little as the following:


supportedOrientations(LANDSCAPE_ANY)

function setup()
    p1=physics.body(CIRCLE, 40)
    p1.x=350
    p1.y=100
    p1.gravityScale=0
    p1.restitution = 0.8
    ground = physics.body(EDGE,vec2(0,10),vec2(WIDTH,10))
    wall1 = physics.body(EDGE,vec2(0,0),vec2(0,HEIGHT))
    wall2 = physics.body(EDGE,vec2(WIDTH,0),vec2(WIDTH,HEIGHT))
    ceiling = physics.body(EDGE,vec2(0,HEIGHT),vec2(WIDTH,HEIGHT))
    
end

function draw()
    background()
    
    sprite("Planet Cute:Rock",p1.x,p1.y)
    
end

function touched(t)
    if t.state==BEGAN 
       and math.abs(t.x-p1.x)<=50 
       and math.abs(t.y-p1.y)<=50 then
        p1.linearVelocity=vec2(math.random(-250,250),600)
        p1.gravityScale=1
     end
end
    
function collide(contact) 
    if contact.state == BEGAN then sound(SOUND_JUMP, 36046) end
end