- Home /
Rotate object after swipe according to swipe direction
Hi, I want my 2D object to rotate (look at) mouse/finger on the screen and after releasing input to start rotating.
I have the code which is doing what I need but in some cases it has a little bug that object starts to rotate in wrong direction(like bouncing of invisible wall).
void LookAtMouse()
{
var ray = new Ray2D(transform.position, Input.mousePosition - transform.position);
var extendedMousePosition = ray.GetPoint(300);
float AngleRad = Mathf.Atan2(extendedMousePosition.y - transform.position.y, extendedMousePosition.x - transform.position.x);
float AngleDeg = (180 / Mathf.PI) * AngleRad;
var mousePos = Input.mousePosition;
var newRotation = Quaternion.Euler(0, 0, AngleDeg - ObjectStartAngle - 1);
this.transform.rotation = Quaternion.Euler(0, 0, AngleDeg - ObjectStartAngle - 1);
Debug.DrawLine(transform.position, mousePos, Color.red);
Debug.DrawLine(transform.position, extendedMousePosition, Color.yellow);
}
And here is my code to get swipe direction if user will release mouse button:
void StartRotation()
{
var ray = new Ray2D(transform.position, Input.mousePosition - transform.position);
var extendedMousePosition= ray.GetPoint(300);
float AngleRad = Mathf.Atan2(extendedMousePosition.y - transform.position.y, extendedMousePosition.x - transform.position.x);
// Get Angle in Degrees
float AngleDeg = (180 / Mathf.PI) * AngleRad;
// Rotate Object
var newRoation = Quaternion.Euler(0, 0, AngleDeg - ObjectStartAngle - 1);
swipeDirection = newRoation.eulerAngles - transform.rotation.eulerAngles;
Debug.Log("Object:" + transform.rotation.eulerAngles);
Debug.Log("Finger:" + newRoation.eulerAngles);
Debug.Log("Swipe direction" + swipeDirection);
}
And here is the problem. Sometimes especially during fast swipes or when user will stop movement at the end then swipeDirection
is calculated incorrectly. I'm strugling with it for 3 days now and I find out that when the bug occur the object is ahead of mouse which seems to be strange..
Here are some gifs for better understanding. Correct behavior:
Incorrect behavior:
If there is any better way to check swipe direction? Or maybe do you know where is the issue in my code?