how to add a speed limit?

foreach (Touch input in Input.touches)
{
if (input.phase == TouchPhase.Moved)
{
Vector3 screenPoint = new Vector3 (Input.mousePosition.x, 65);
screenPoint.z = 11; //distance of the plane from the camera
transform.position = Camera.main.ScreenToWorldPoint(screenPoint);
}
}

The object follows the touch, but how do I get it moving with a velocity from position A to position B?

1 Answer

1

You could do it using Lerp.

public float speed = 5f;

private Vector3 origin;
private Vector3 destination;
private float timeToTravel = 0f;
private float currentTime = 0f;
private bool isMoving = false;

WhateverMethod()
{
    ...

    foreach (Touch input in Input.touches)
    {
        if (input.phase == TouchPhase.Moved)
        {
            origin = transform.position;

            Vector3 screenPoint = new Vector3 (Input.mousePosition.x, 65);
            screenPoint.z = 11; //distance of the plane from the camera
            destination = Camera.main.ScreenToWorldPoint(screenPoint);

            timeToTravel = (origin - destination).magnitude / speed;
            isMoving = true;
        }
    }

    ...
}

void Update()
{
    if (isMoving)
    {
        currentTime += Time.deltaTime;
        
        if (currentTime <= timeToTravel)
        {
            transform.position = Vector3.Lerp(origin, destination, currentTime / timeToTravel);
        }
        else
        {
            transform.position = destination;
            currentTime = 0f;
            isMoving = false;
        }
    }
}

There are cleaner ways to do it, but this will work.

That's great! it works perfectly! I heartily thank you <3

–

This script works for one player, but for two players playing versus?

–

That would be a completely different question. You will have to set different variables for each player, or even better, put the component in both player objects. Once done that, you have to control the touches to see which player has done the input, which depends on how you detects which player has done it. If you can, please accept the answer for this question. For more insight on how to detect which player has done an input, post another question.

–