It sounds like there are two different tasks here:
1) Getting the mouse's position relative to the parent object (where you want the childobject attached, right?).
2) Drawing the child object in-game while being able to rotate its position and Texture.
Solving 1 is pretty simple:
To get direction from object to mouse as a Vector2, subtract object's position (a Vector2) from mouse's position (also a Vector2):
Vector2 distanceAndDirectionFromObjectToMouse = mousePosition - objectPosition;
This value you can store along with the child object, to know where to draw it in relation to the parent.
Solving 2) is more complicated.
You want to be able to rotate the child object's position around the parent.
To do this you need to:
- Find the current rotation of and distance to the child object
- change the rotation by the wanted amount
- calculate the new position using cos and sin (you may want to read up on these)
basically cos(angle) gives you the X coordinate of where to position something, and sin(angle) gives you the Y coordinate.
Getting the rotation of a Vector2 is possible using the Atan2 function:
private float Vector2ToRadian(Vector2 direction)
return (float)Math.Atan2(direction.X, -direction.Y);
Radian is a type of measurement where there are 2 * PI degrees (approximately 6.283) around the full circumference of the circle as opposed to regular degrees where you have 360.
Getting the distance is a method on the Vector2 struct called Length().
float distanceToChild = distanceAndDirectionFromObjectToMouse.Length();
using the distance and rotation you can use the following method to find the new location of the child object (the "sattelite" in the methodname below):
public Vector2 GetPositionOfSatellite(Vector2 center, float distance, float directionInRadians)
float yDifference = (float)Math.Sin(directionInRadians);
float xDifference = (float)Math.Cos(directionInRadians);
Vector2 direction = new Vector2(xDifference, yDifference);
Vector2 precisePositionOfSatellite = center + direction * distance;
If that is unclear, you may benefit from the two articles I've taken code from:
...otherwise, just ask
Kind regards - Jakob
Edited by xnafan, 08 January 2014 - 03:17 AM.