jasmine zhao
jasmine zhao

Reputation: 93

rotate to difference angle when first click

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??

Upvotes: 0

Views: 31

Answers (2)

derHugo
derHugo

Reputation: 90833

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

Upvotes: 2

h4ri
h4ri

Reputation: 369

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.

Upvotes: 2

Related Questions