Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
480 views
in Technique[技术] by (71.8m points)

c# - Drag to move at unity and hold touch to keep moving at same direction

So im trying to write a code to move player with dragging on screen but i want player to keep moving at same direction when i hold my finger and only stops when i take my finger away. ive written this code and player moves but it stops when i hold my finger.

void Update()
{
    if (Input.touchCount > 0)
    {
        touch = Input.GetTouch(0);

        if (touch.phase == TouchPhase.Moved)
        {
            transform.position = new Vector3(
                transform.position.x + touch.deltaPosition.x * speedModifier,
                transform.position.y,
                transform.position.z + touch.deltaPosition.y * speedModifier);
        }
    }
}
question from:https://stackoverflow.com/questions/65617715/drag-to-move-at-unity-and-hold-touch-to-keep-moving-at-same-direction

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If I understand you correctly you could store the last swipe movement and use it also for a stationary touch like e.g.

Vector2 currentDirection;

void Update()
{
    if (Input.touchCount > 0)
    {
        touch = Input.GetTouch(0);

        switch (touch.phase)
        {
            case TouchPhase.Moved:
                currentDirection = touch.deltaPosition * speedModifier;
                transform.position += currentDirection;
                break;

           case TouchPhase.Stationary:
               transform.position += currentDirection;
               break;

           default:
               currentDirection = Vector2.zero; 
               break;
        }
    }
}

This way it continuous to move with the last swipe velocity.

However, in general you should also take the Time.deltaTime into account to be frame-rate independent.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...