Rotate UI elements in direction of drag

I have UI elements that are dragged around, and I want to make them feel a bit more satisfying to move. This is the (functional) script I have to make them follow the mouse position.

public void OnDrag(PointerEventData data) {
        Vector3 mousePos = new Vector3(data.position.x, data.position.y, 0);
        // Vector3 direction = Vector3.Normalize(mousePos - transform.position);

        transform.position = mousePos;
}

What I want to do is to rotate the elements slightly in the direction of movement, so react to the direction and speed with which the player is moving them. The commented line tracks the direction, but I can’t really find a good way to have it rotate according to the direction. I haven’t found a good way to track the speed, either.

Does anyone have suggestions for a solution?

I think the first thing to do is explain what this means:

… because cartesian-direction-to-rotational-angle is dead easy: just use Mathf.Atan2() with y/x inputs, then you get the angle (heading) of any particular pair of coordinates, such as movement.

You can also simply drive one of the cardinal transform shortcuts: You may be able to simply drive transform.forward (or transform.up when in 2D) equal to your movement vector.

How to use Mathf.Atan2() to derive heading from cartesian coordinates:

https://discussions.unity.com/t/769743/4

Sine/Cosine/Atan2 (sin/cos/atan2) and rotational familiarity and conventions

https://discussions.unity.com/t/863372/8

1 Like