Sprites and Tweens

Hi. I am new to programming and learning Codea. Any help will be appreciated. I tried to use a sprite as a subject for tween function and I got an error message saying: “you can only use table or user data for subject”. Is there any other way for using tween function for sprites?

Yes, it’s normal you can’t use a sprite as a Subject for tween function, use a table.
For example create a table and load your sprite in the setup function :

mySprite = readImage("Document:xxxx.png")
position = {x = 0, y = 0}

Then, use the tween function on your table “position” also in the setup function :

tween(5.0, position, { x = 300, y = 300 })

So x and y in position will go to 300 in 5 secondes.
You can now draw your sprite in the draw function :

sprite(mySprite, position.x, position.y)

Normally your sprite should move from (0, 0) to (300, 300).

Hope you’ll understand what I said, if yes read the animation sample for understand more functionalities of tween function. :wink:

Thank you very much. This information has been very useful indeed.

I am trying to move my sprite to where I touch the screen but I can’t. What is wrong with my code?

function setup()
    supportedOrientations(CurrentOrientation)
    theSprite=readImage("Planet Cute:Character Boy")
    position = {x=0, y=0}
    px=300
    py=300
    tween(5.0, position, { x=px, y=py })
    
    end


function draw()
    background()
    sprite("SpaceCute:Background",374,374)
    sprite(theSprite,position.x,position.y)
   
   px = CurrentTouch.x
   py = CurrentTouch.y
    
 end

This is all you need to move a sprite where you move your finger.


function setup()
    supportedOrientations(CurrentOrientation)
    theSprite=readImage("Planet Cute:Character Boy")
end

function draw()
    background()
    sprite("SpaceCute:Background",374,374)
    sprite(theSprite,CurrentTouch.x,CurrentTouch.y)
 end

Try something like this…

function setup()
    supportedOrientations(CurrentOrientation)
    theSprite=readImage("Planet Cute:Character Boy")
    position = vec2(300, 300)
end

function draw()
    background()
    sprite("SpaceCute:Background",374,374)
    sprite(theSprite,position.x,position.y)
end

function touched(touch)
    if touch.state == BEGAN then
        tween.stopAll()
        tween(1, position, { touch.x, touch.y })
    end
end

Thank you both. Mark, That’s exactly what I was trying to do.