0
\$\begingroup\$

I want to make a 3d object rotate smoothly when being dragged in a ui in Unity. My stuff currently works but I just can’t get it to rotate smoothly, I can only make it rotate instantly which looks bad. So my question: How do I make the Object rotate smoothly if this code here makes it rotate instantly?

void IDragHandler.OnDrag(PointerEventData eventData)
    {
        mousePositionDelta = Mouse.current.delta.ReadValue();

        float dotProduct = -Vector2.Dot(mousePositionDelta, uiCamera.transform.right);
        characterModelTransform.Rotate(transform.up, dotProduct * characterRotationModifier);

        prevMousePosition = eventData.position;
    }

Thank you for any answers in advance ^^

\$\endgroup\$
1
  • \$\begingroup\$ It's not immediately obvious to me what this code is meant to accomplish. Try describing from a player's eye view, which way should this object turn to face as they drag it? A diagram or screenshot can often help. \$\endgroup\$
    – DMGregory
    Sep 26, 2023 at 21:15

2 Answers 2

0
\$\begingroup\$

It seems strange you are updating prev mouse position if you use some other function to get mouse deltas.

I also strongly suspect you are tripping over different spaces, as the mouse deltas are most likely aligned with the screen and doing a dot product with a 3D vector in Unity space makes no sense.

If you want to smooth out the rotation being applied you can keep a parameter, say float targetRotation which you will modify in the function you show. Then in Update you can use Mathf.SmoothDampAngle to change the transform smoothly.

\$\endgroup\$
0
\$\begingroup\$

I think I understand what you want to do. This is not pretty, but it works to smoothly start and end rotation from the mouse drag.

public GameObject Target;  //GameObject to rotate

[Range(0.1f,1f)]
public float smoothTime = 0.3f;

float CurrentSpeed = 0f;
float WantedSpeed  = 0f;
float SpeedInc     = 0f;
float Velocity = 0.0f;

public void OnDrag(PointerEventData eventData)
{
    SpeedInc += eventData.delta.x;  // Find the mouse delta x. 
}

void Update()
{
    WantedSpeed -= SpeedInc * Time.deltaTime;
    WantedSpeed = Mathf.SmoothDamp(WantedSpeed, 0, ref Velocity, smoothTime);
    SpeedInc = 0;
    Target.transform.Rotate(Target.transform.up,WantedSpeed,Space.Self);
}
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .