I need a help with a script where I am smoothly rotating the model in the y direction with mouse drag. The rotation works well as expected, however if I drag the mouse faster, then the model spins for longer time. I do not want this. The spin time should remain the same throughout.
How do I control my _rotationVelocity to have a maximum limit?
using System.Collections.Generic;
using System.Collections;
using UnityEngine.EventSystems;
using UnityEngine;
public class RotateModel : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler {
public GameObject model;
public float rotationSpeed;
public float rotationDamping;
private float _rotationVelocity;
private bool _dragged;
public void OnBeginDrag (PointerEventData eventData) {
_dragged = true;
}
public void OnDrag (PointerEventData eventData) {
_rotationVelocity = eventData.delta.x * rotationSpeed;
model.transform.Rotate (Vector3.up, -_rotationVelocity, Space.Self);
}
public void OnEndDrag (PointerEventData eventData) {
_dragged = false;
}
private void Update () {
if (!_dragged && !Mathf.Approximately (_rotationVelocity, 0)) {
float deltaVelocity = Mathf.Min (
Mathf.Sign (_rotationVelocity) * Time.deltaTime * rotationDamping,
Mathf.Sign (_rotationVelocity) * _rotationVelocity
);
_rotationVelocity -= deltaVelocity;
model.transform.Rotate (Vector3.up, -_rotationVelocity, Space.Self);
}
}
}
so delta.x should be an either -1, 0, or 1 aka mathf.sign.
so before you use eventData.delta.x use eventData.delta.x = Mathf.Sign(eventData.delta.x)
or just embed into the _rotationVelocity. _rotationVelocity = Mathf.Sign(eventData.delta.x) * rotationSpeed;
As for the reason why it might be spinning faster, is because say mouse x is 0.5f, then you’ll get different speed at mouse x at 1f.
Note that mouse delta is not in the range -1 to 1. Mouse delta can be as large as it gets. If the user has a high mouse speed and moves the mouse 300km between two frames the delta would be huge. So generally at fast mouse movements, delta will almost always be greater than 1 (or smaller than -1). So you don’t have to clamp it to 1, but a reasonable value that makes sense for the usecase, so you don’t get that huge differences. Maybe only clamp the velocity once you let go of the mouse button. So just have the initial velocity not that huge so it doesn’t take ages to slow down.
The OP specifically uses a linear slowdown. For such cases a non linear slowdown can sometimes be better as it handles really large values more or less automatically. Though this completely depends on the usecase.
haha coming back to this after 1.5 years and i have to recollect what and how i did it
But yeah this is exactly how I had done using Mathf.Clamp and using min and max rotation values.