LiveCode Support
LiveCode Support

Reputation: 177

How do you move an object in LiveCode by a given amount of pixels?

When working on my stack, during edit mode I am able to nudge any controls via the arrow keys.

I have had some success moving control when my stack is running with the "move" command e.g

 move button 1 to 100,100

Are there any more efficient ways to move controls during runtime?

Upvotes: 0

Views: 1136

Answers (2)

Devin
Devin

Reputation: 603

If you are asking how to use the arrow keys to nudge objects while in run (browse) mode, here is one approach (handler would go into the card script):

on arrowKey pWhich
  # determine some way to designate which object is to be nudged
  put the long id of btn "test" into tSelObj # for example
  switch pWhich
    case "left"
      put -1 into tXamount
      put 0 into tYamount
      break
    case "up"
      put 0 into tXamount
      put -1 into tYamount
      break
    case "right"
      put 1 into tXamount
      put 0 into tYamount
      break
    case "down"
      put 0 into tXamount
      put 1 into tYamount
      break
  end switch
  move tSelObj relative tXamount,tYamount
end arrowKey

Upvotes: 1

Benjamin Beaumont
Benjamin Beaumont

Reputation: 910

There are a variety of methods you can employ depending on how smooth you want the animation to be. At the simplest level you need to move the objects in script by setting their position related properties: top, left, right, bottom, loc and rect.

set the top of button 1 to 10

If you're moving an object in more than 1 direction you'll want to do something like this:

on moveObject
   lock screen
   lock messages

   set the top of button 1 to 10
   set the left of button 1 to 20

   unlock messages
   unlock screen
end moveObject

If you want continuous animation you'll want to make it loop using something like this:

on moveObject
   lock screen
   lock messages

   local tX, tY
   # Calculate new position (tX and tY)

   # Move objects
   set the loc of button 1 to tX, tY

   unlock messages
   unlock screen

   # If animation is not finished, loop
   if tEndCondition not true then
      send "moveObject" to me in 5 milliseconds
   end if
end moveObject

Finally, if you want a really smooth animation you'll want to expand this loop to calculate the position of objects based on time:

on animationLoop pTime
   lock screen
   lock messages

   local tX, tY
   # Calculate new position (tX and tY) based on time

   # Move objects
   set the loc of button 1 to tX, tY

   unlock messages
   unlock screen

   if tEndCondition not true then
      # Calculate when the next frame should be based on your target frame rate
      send "moveObject" && tTime to me in tNextFrameTime
   end if
end animationLoop

The final approach provides a means for frames to be skipped if a certain frame took too long to calculate and render. The end result is a smooth animation that reflects the users expectation.

Upvotes: 2

Related Questions