So, I found some code to essentially have a rectangle follow the mouse around my player object at a set distance. On a 2D plane, I have the character, and when the player clicks the mouse button, a shield will appear between the mouse and the character. This part works, and here is the code:
var angle;
var track_radius = 10;
// find the angle to the mouse
angle = point_direction(self.x, self.y, mouse_x, mouse_y);
// turn the shield to look at the mouse
image_angle = angle;
// convert to radians for the math functions
angle = degtorad(angle);
// place the shield on a circular track about the player
// . track_radius is set in the create event
x = global.playerX + 50 * cos(angle);
y = global.playerY - 50 * sin(angle); // minus
So, the problem comes in when the mouse comes close to the shield. The shield splits into two, mirrored across the mouse pointer, flickering back and forth. The problem continues basically anytime the mouse is near or within the radius where the shield exists. It's also probably worth noting that the shield is created AT the position of the player when the mouse is clicked, and then moved using the above code. Thoughts?
angle = point_direction(self.x, self.y, mouse_x, mouse_y);
This code is calculating the angle from the shield to the mouse pointer, because self
currently refers to the shield.
x = global.playerX + 50 * cos(angle);
y = global.playerY - 50 * sin(angle); // minus
Here you set the position of the shield relative to the player, so that the angle from the player to the shield equals the angle that you calculated above.
Now consider the situation where the mouse is close to the shield, and the direction from the shield to the mouse is different than the direction from the player to the mouse. In the bad ASCII graphic below, imagine the O is the player, the ) is the shield and the ^ is the mouse cursor.
O ------ )
^
The shield is directly to the right of the player (0°), but the mouse is directly below the shield (270°). Therefore your code will place the shield directly below the player (remember, angle
in your code is the direction from the shield to the mouse)
O
| ^
|
|
)
In the next step, the code again takes the direction from the shield to the mouse. This time it's more like 45° above the shield, so the shield will be placed 45° above and to the right of the player.
This jumping back and forth happens a few times with changing positions, until the shield "settles" in two alternating positions around the mouse cursor.
To come to the solution, you want to use the direction from the player to the mouse cursor to determine your shield position, not the direction from the shield to the mouse cursor. But I have to say that the dynamics of the system you accidentally created are somewhat interesting :)