Reputation: 2468
I am struggling to get this right. What I want to do is to move a panel(10px by 10px) to another panel which is the same size.
I want to see how it moves to the other panel... and I achieved this using a timer.
My code works, but I do have a problem I cannot get past...
Most of the time the panel that is moving, first reaches the x or y coordinate and then move in a horizontal or vertical line to the other panel.
This looks OK when moving very fast... but when moving slowly I can see that it looks very wrong.
This is just a small paint job i have created to show you what i have in mind:
I want point B to move to point A in a straight line.
CODE:
private void timer_Tick(object sender, EventArgs e)
{
smallX = pnlTo.Location.X;
smallY = pnlTo.Location.Y;
largeX = pnlFrom.Location.X;
largeY = pnlFrom.Location.Y;
//Should we find the ratio??
// ####### X #######
if (largeX != smallX)
{
int xRatio;
if (largeX > smallX)
{
//If 'large' is to the right.
//Find ratio.
xRatio = largeX / smallX;
pnlFrom.Left -= xRatio;
}
else
{
//If 'large' is to the left.
//Find ratio.
xRatio = smallX / largeX;
pnlFrom.Left += xRatio;
}
}
// ####### Y #######
if (largeY != smallY)
{
int yRatio;
if (largeY > smallY)
{
//If 'large' is to the bottom.
yRatio = largeY / smallY;
pnlFrom.Top -= yRatio;
//pnlFrom.Top -= pixelsToMove;
}
else
{
//If 'large' is to the top.
yRatio = smallY / largeY;
pnlFrom.Top += yRatio;
//pnlFrom.Top += pixelsToMove;
}
}
lblLargeX.Text = pnlFrom.Location.X.ToString();
lblLargeY.Text = pnlFrom.Location.Y.ToString();
if (largeX == smallX && largeY == smallY)
{
timer.Stop();
}
}
I know I am very wrong with how to achieve this... but can someone please help me in the right direction?
Thank you in advance.
Upvotes: 2
Views: 2140
Reputation: 21999
I've no idea how your algorithm should work and what mistakes are (either in logic or in implementation), but moving from (x1;y1)
to (x2;y2)
is simple:
int steps = 10; // how many steps animation/timer will have
int x = x1 + (x2 - x1) * step / steps;
int y = y1 + (y2 - y1) * step / steps;
Notes:
(x,y)
is coords at given stepstep
is current step in the range: from 1 to steps
delta
algorithm, for which you must use float
/double
and only store delta
and steps
);Upvotes: 1
Reputation: 355
You might find a smoother way is to check the difference in X and Y before beginning, then using that divided by how many steps you want to make as a 'velocity'. So, if you want to move in 10 ticks, calculate LargeY and SmallY, then divide that by ticks and set a class level variable to that amount. Each tick increment by that amount.
Upvotes: 0