How can I implement snapping via code? I have this 2d circle that the players rotate via drag and it works like a rotating dial. The best way to describe what I wanted to achieve is similar to a clock hand snapping to the hour numbers. I'm a total beginner and haven't actually learned anything about quaternions.
This is the my code , im using a raycast to detect if the dial is clicked/dragged.
Vector2 worldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(worldPoint, Vector3.forward);
if (Input.GetMouseButtonDown(0))
{
if (hit.collider && hit.collider.GetComponent<Rotate2d>())
{
deltaRotation = 0f;
previousRotation = angleBetweenPoints(transform.position, Camera.main.ScreenToWorldPoint(Input.mousePosition));
}
}
else if (Input.GetMouseButton(0))
{
if (hit.collider && hit.collider.GetComponent<Rotate2d>())
{
currentRotation = angleBetweenPoints(transform.position, Camera.main.ScreenToWorldPoint(Input.mousePosition));
deltaRotation = Mathf.DeltaAngle(currentRotation, previousRotation);
if (Mathf.Abs(deltaRotation) > deltaLimit)
{
deltaRotation = deltaLimit * Mathf.Sign(deltaRotation);
}
previousRotation = currentRotation;
hit.collider.gameObject.transform.Rotate(Vector3.back * Time.deltaTime, deltaRotation);
}
}
I forgot to add, here is my angle between points method.
float angleBetweenPoints(Vector2 position1, Vector2 position2)
{
Vector2 fromLine = position2 - position1;
Vector2 toLine = new Vector2(1, 0);
float angle = Vector2.Angle(fromLine, toLine);
Vector3 cross = Vector3.Cross(fromLine, toLine);
// did we wrap around?
if (cross.z > 0)
{
angle = 360f - angle;
}
return angle;
}
hit.collider.gameObject.transform.Rotate(Vector3.back * Time.deltaTime
it's not meaningful to multiply a direction vector by time here. You do not want time in this expression at all. \$\endgroup\$