views:

280

answers:

2

I have drawn an image in the device context using python, and i want to move it somothly/animate either vertically or horizontally? What algorithm should i use?

Where can i get info for this kind of tasks in python?

+1  A: 

Once an object is drawn in a device context it stays there. If you want to move it you need to redraw it.

You can keep a background that's fixed and only redraw the movable elements each time they move. Basically that's how it's done.

To move an object smoothly over a line you have to do something like this (I don't have a program ready, so can only give you an idea):

  • choose the start and end position: point A(x1, y1) and B(x2, y2)
  • choose in how much time the object should change position from A to B (say 10 seconds).
  • use a timer set to a certain interval (say 2 seconds)
  • calculate the delta X and Y that the object should change for each timer interval. In this case dx = (x2-x1)*2/10 and dy = (y2-y1)*2/10
  • in the timer callback increment the current object position with dx and dy and redraw the image

That would be the algorithm.

I suggest that you also take a look to PyGame. Maybe you can use that and it also has some tutorials.

rslite
Exactly! i need the information on how to change the calculated values of coordinates smoothly over time ....
gath
A: 

To smoothly move object between starting coordinate (x1, y1) and destination coordinate (x2,y2), you need to first ask yourself, how long the object should take to get to its destination. Lets say you want the object to get there in t time units (which maybe seconds, hours, whatever). Once you have determined this it is then trivial to workout the displacement per unit time:

dx = (x2-x1)/t
dy = (y2-y1)/t

Now you simply need to add (dx,dy) to the object's position ((x,y), initially (x1,y1)) every unit time, and stop when the object gets within some threshold distance of the destination. This is to account for the fact errors in divisions will accumulate, so if you did an equality check like:

(x,y)==(x2,y2)

It is unlikely it will ever be true.

Note the above method gives you constant velocity, straight line movement. You may wish to instead use some sort a slightly more complex formula to give the object the appearance of accelerating, maintaining cruise speed, then decelerating. The following formulae may then be useful:

v(t) = u(t) + t*a(t)
x(t) = v(t) + t*v(t)

This is merely Euler's method, and should suffice for animation purposes.

freespace