- Home /
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?
Answer by dmg0600 · Sep 20, 2014 at 11:25 AM
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.
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.
Your answer
![](https://koobas.hobune.stream/wayback/20220613163403im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Touch the screen and jump two time with the same height 1 Answer
Android: move character where I touch the screen 1 Answer
Game Object Follow finger 1 Answer
Instantiate not working 1 Answer
Android Drag By Steps 0 Answers