animation

alien

Member
Joined
Mar 21, 2006
Messages
24
a simple question. how do i move a rectangle which i have drawn on a picturebox from one position to another?
 
Assuming you wish to move in a direct line. One method is to calculate how many steps you wish to take, calculate how far the rectangle will move on each step. Then create a loop that operates for the amount of steps, on each loop move the offset the rectangles position and redraw. As this will happen near instantaneously you will need to pause for awhile too.
C#:
// given
Rectangle rect = new Rectangle (0, 0, 50, 50)
Point target = new Point(200, 200)

// create 8 movement frames
Point totalOffset = new Point(target.X - rect.X, target.Y - rect.Y)
Point movementVector = new Point(totalOffset.X / 8, totalOffset.Y / 8)

for(int i = 0; i < 8; i++)
{
    // shift the rectangle
    rect.Offset(movementVector);

    // assumes your paint code simply draws a rectangle at point rect
    Refresh();
    
    // wait awhile before making next anim step
    System.Threading.Thread.Sleep(50);
}
Depending on what your doing depends on the actual loop method. Instead of a simple loop in this manner you could also use a timer and move on each tick untill at the required destination. Alternatively you could do the same thing but with a game loop that calculates its own framerate. In any case the theory is the same, calculate the displacement vector, then on each frame untill target is reached move your object.
 
Back
Top