I'm making a simple game in C# for practice and i'm having some problems when dragging a sprite and making another sprite follow it.
What i'm trying to achieve:
When dragging a sprite, i want another sprite to move with it.
While dragging, i want the two sprites to keep the same distances they where before from one another.
If possible, but not related to the question, i would like to adjust this distance with another offset.
Example:
- Lets suppose i have two sprites, one at position (10, 10) and another at (10, 20).
- If i drag the first sprite to (10, 20) the second sprite should be at (10, 30).
Example code of what i'm trying to do:
public class Drag
{
public Sprite first;
public Sprite second;
public bool dragging = true;
public Point mouse_position;
public void Update()
{
if (dragging == true)
{
first.position = mouse_position;
var offset = ???
var another_offset = ???
second.position = ???
}
}
}
Edit: I tried the code that @DMGregory posted and @Tyyppi_77 linked but it is not working as expected. Here is the code that i'm using. Currently, the second sprite is flying all over the place.
public class Sprite
{
public Sprite parent;
public List<Sprite> childrens;
public Rectangle bounds;
public Point World { get { return new Point(bounds.X, bounds.Y); } }
public Point Local { get { return new Point(World.X - parent.World.X, World.Y - parent.World.Y); } }
}
public class Drag
{
public Sprite first;
public Sprite second;
public Point mouse;
public bool dragging;
public void Update()
{
if (dragging == true)
{
first.bounds.X = mouse.X - (first.bounds.Width / 2);
first.bounds.Y = mouse.Y - (first.bounds.Height / 2);
second.bounds.X = second.Local.X;
second.bounds.Y = second.Local.Y;
}
}
}
Thanks in advance!