Search code examples
c#unity-game-enginetouchscale

Decreasing scale depending on touch movement speed


I want my object scale to decrease depending on touch movement speed.

Here's my script that didn't work:

if (Input.touchCount > 0 && canRub)
    {
        Touch touch = Input.GetTouch(0);
        if (touch.phase == TouchPhase.Moved)
        {
            scaleX -= transform.localScale.x / (strengthFactor * sM.durabilityForce);
            scaleY -= transform.localScale.y / (strengthFactor * sM.durabilityForce);
            scaleZ -= transform.localScale.z / (strengthFactor * sM.durabilityForce);
            transform.localScale = new Vector3(scaleX, scaleY, scaleZ);
        }
    }

For example if move finger slowly object will reach his scale.x == 0.3 for 5 seconds, but if he move his finger fast enough, he will achieve this scale for 3 seconds.


Solution

  • You should rather make the scaling depended on the Touch.deltaPosition which is the delta the touch was moved since the last frame.

    The position delta since last change in pixel coordinates.

    The absolute position of the touch is recorded periodically and available in the position property. The deltaPosition value is a Vector2 in pixel coordinates that represents the difference between the touch position recorded on the most recent update and that recorded on the previous update. The deltaTime value gives the time that elapsed between the previous and current updates; you can calculate the touch's speed of motion by dividing deltaPosition.magnitude by deltaTime.

    So you could do something like e.g.

    public float sensibility = 10;
    
    if (Input.touchCount > 0 && canRub)
    {
        Touch touch = Input.GetTouch(0);
    
        if (touch.phase == TouchPhase.Moved)
        {
            var moveSpeed = Touch.deltaPosition.magnitude / Time.deltaTime;
            // since moveSpeed is still in pixel space 
            // you need to adjust the sensibility according to your needs
            var factor = strengthFactor * sM.durabilityForce * moveSpeed * sensibility;
    
            scaleX -= transform.localScale.x / factor;
            scaleY -= transform.localScale.y / factor;
            scaleZ -= transform.localScale.z / factor;
    
            transform.localScale = new Vector3(scaleX, scaleY, scaleZ);
        }
    }