'Rotate and reset object rotation with Mouse Input
I would like to rotate my game object with mouse input but the problem is once I decided to move the mouse in the opposite direction I would like to reset the rotation of GameObject like Quarterion.identity(0,0,0) and then keep the rotation to the other side.
When I release the mouse button, it does what I want it to do, but I'd like to capture this smoothness also in GetMouseButton() , If that doesn't make clear, I explained the idea with picture. All I want to do is make realistic physics.
Picture if it doesn't show up: https://i.stack.imgur.com/DXgKt.png
if (Input.GetMouseButton(0))
{
swipe= Input.mousePosition.x - mouseStartPos;
player.transform.Rotate(0, swipe* 5 * Time.deltaTime, 0f);
}
if (Input.GetMouseButtonUp(0))
{
swipe= 0;
player.transform.DORotate(new Vector3(0, 0, 0), 0.1f, RotateMode.Fast);
//It is returning to the base rotation which I want in GetMouseButton(), if(swipe==0){} strategy was ineffective. It is constantly changing swipe to 0, resulting in no rotation...
Thank you from now and have a good day, I hope I will get the idea in order to make it.
I tried a lot of different rotation types but couldn't get the desired outcome.
Solution 1:[1]
You can try this:
float? startX;
float? currentX;
void Update()
{
// Set the starting position
if (Input.GetMouseButtonDown(0))
{
startX = Input.mousePosition.x;
}
// Ensure no action when startX is not set
if (startX == null)
return;
// Rotate while the mouse is moving
if (Input.GetMouseButton(0))
{
// Ensure Position Changed
if (Input.mousePosition.x == currentX)
return;
currentX = Input.mousePosition.x;
// Turn it in the required direction
// Get a vlue of -1 or 1
var dir = (currentX.Value - startX.Value) / Mathf.Abs(currentX.Value - startX.Value);
// Rotate
player.transform.Rotate(0, dir * 5 * Time.deltaTime, 0f);
}
if (Input.GetMouseButtonUp(0))
{
startX = null;
currentX = null;
player.transform.DORotate(new Vector3(0, 0, 0), 0.1f, RotateMode.Fast);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |

