Home > Mobile >  rotate to difference angle when first click
rotate to difference angle when first click

Time:11-02

i use this code to rotate my gameobject, but the problem is when i first click , the gameobject rotate to the difference angle.then work find.

    private Vector3 _prevPos;
    private Vector2 ret;
if (Input.GetMouseButton(0))
    {
         ret = Input.mousePosition - _prevPos;
         _prevPos = Input.mousePosition;


         transform.Rotate(ret.y / 10, 0, ret.x );

    }

In debug , "ret.y" 's number is no 0 when i first click.

how can i fix this problem??

CodePudding user response:

As correctly mentioned here in the initial frame you are rotating with the pure Input.mousePosition.

In order to avoid that wrong delta you could treat the initial case extra

if(Input.GetMouseButtonDown(0))
{
    _prevPos = Input.mousePosition
}
else if (Input.GetMouseButton(0))
{
    ret = Input.mousePosition - _prevPos;
    _prevPos = Input.mousePosition;

     transform.Rotate(ret.y / 10, 0, ret.x );
}

The first block is now executed in the very first frame of the press, the second block in all other frames while the button stays pressed

CodePudding user response:

The problem is that _prevPos is (0,0), so for the first time ret will be Input.mousePosition.

You have to keep _prevPos updated when there are no inputs, because there will be the same problem, when you release the button, move the mouse elsewhere, and click again.

Move _prevPos = Input.mousePosition to the end of Update.

  • Related