[SOLVED] speed increase only when button is pressed(touch)

I want to increase object’s speed only when the button is pressed(touched), it should come back to normal speed when the button is not pressed(touched).

transform.Translate(direction * Time.deltaTime * speed);

I tried this;

public void SpeedUp()
{
speed * 10;
}

and added this to the button. Speed is increasing when the button is pressed but not coming back to normal when button is left.

You’re going to have to show more code. Right now what you show doesn’t actually do anything. Speed doesn’t increase there. You’re doing a simple math problem but not assigning the value back to speed.

Don’t forget to use code tags! Using code tags properly - Unity Engine - Unity Discussions

public bool fingerHold = false;
public Vector2 startPos;
public Vector2 endPos;
public float speed = 1f;
public void Update() {
        PlayerMove ();
    }
void PlayerMove(){
      
        if (Input.touchCount > 0)
        {
            Touch touch = Input.GetTouch(0);
            if (touch.phase == TouchPhase.Began)
            {
                startPos = touch.position;
                endPos = touch.position;
                fingerHold = true;
            }
            else if (touch.phase == TouchPhase.Moved)
            {
                endPos = touch.position;
            }
            else if (touch.phase == TouchPhase.Ended)
            {
                fingerHold = false;
            }
        }
        if (fingerHold)
        {
            float deltaX = endPos.x - startPos.x;
            float deltaY = endPos.y - startPos.y;
            Vector2 direction = new Vector2(deltaX, deltaY).normalized;
            transform.Translate(direction * Time.deltaTime * speed);
        }
//This is what I have assigned to the SpeedUp button
public void SpeedUp(){
        speed = speed * 20;
    }

So, it looks like you have the right idea going. Right now I don’t see you calling SpeedUp, so your speed isn’t going to increase.

So, you just need to apply speedUp somewhere, and then if you want a complete return to 1f, you could do that in TouchPhase.Ended. If you want to reduce over time, you could have a speedDown method that also makes sure that you never go below 1f. That will handle it for you.

That SpeedUp function is assigned to a button UI and it’s working when that button is pressed. And for button we don’t use touch.phase. It works without doing that.

You could try changing from assignment to the button event to using the IPointerDown/IPointerUp interfaces.
Set speed up & down on those.
As @Brathnann mentioned, you could use a slowdown routine if you’d like, also.

This may require that you check that your touch isn’t hitting the button for your other calculations.

Here is the solution for this problem.

http://answers.unity3d.com/questions/1392721/speed-increase-only-when-button-is-pressedtouch.html?childToView=1394474#comment-1394474

That’s what I said? :slight_smile: heh. Glad ya got it working.