I'm trying to move pictureboxes(NPCs) automatically towards to main character(pictureBox1), basically I want them to chase pB1. I'm very new to vectors. I couldn't understand the logic very well. First, let me show the codes.
int pictx,picty,mcx,mcy;
private void Monster_drag_Tick(object sender, EventArgs e)
{
foreach (var pict in this.Controls.OfType<PictureBox>())
{
pictx = pict.Location.X;
picty = pict.Location.Y;
mcx = pictureBox1.Location.X;
mcy = pictureBox1.Location.Y;
if (pict.Name != "pictureBox1")
{
ChaseVector(mcx, mcy, 0.5f);
}
}
}
This was the timer event. Interval is 1000 by the way. Also I have a Struct that automatically creates pictureboxes. I'm pulling all pictureboxes that created with Struct by foreach as you can see.
And here is the Vector method;
public void ChaseVector(int x, int y, float speed)
{
float tx = x - pictx;
float ty = y - picty;
double length = Math.Sqrt(tx * tx + ty * ty);
if (length < speed)
{
// move towards the goal
pictx = (int)(pictx + speed * tx / length);
picty = (int)(picty + speed * ty / length);
foreach (var pict in this.Controls.OfType<PictureBox>())
{
if (pict.Name != "pictureBox1")
{
pict.Location = new Point(pictx, picty);
}
}
}
else
{
// already there
pictx = x;
picty = y;
foreach (var pict in this.Controls.OfType<PictureBox>())
{
if (pict.Name != "pictureBox1")
{
pict.Location = new Point(pictx, picty);
}
}
}
}
I found this code on the stackoverflow. I really don't know anything about vectors. This code makes pictureboxes jump to main character. Flash them basically. I want them to chase mc slowly, like walking I mean. As if there is no speed, they are just jumping over the mc every time I move the character.
Waiting for your helps and if there is a better way to use Vectors please tell. Thanks in advance.