UPDATE:
Use this:
private const float MOVEMENT_TIME = 2.0f; // The object moves for 2 seconds
private const float MOVEMENT_DISTANCE = 10.0f; // Distance the object should move
void Update()
{
if(Input.GetKeyDown(KeyCode.A))
{
StopCoroutine("MoveObject");
StartCoroutine("MoveObject", MOVEMENT_DISTANCE);
}
if(Input.GetKeyDown(KeyCode.D))
{
StopCoroutine("MoveObject");
StartCoroutine("MoveObject", -MOVEMENT_DISTANCE);
}
}
private IEnumerator MoveObject(float distance)
{
Vector3 currentPosition = this.transform.position;
Vector3 targetPosition = new Vector3(this.transform.position.x + distance, this.transform.position.y, this.transform.position.z);
float currentTime = 0.0f;
while(currentTime <= MOVEMENT_TIME)
{
float movementFactor = currentTime / MOVEMENT_TIME;
this.transform.position = Vector3.Lerp(currentPosition, targetPosition, movementFactor);
currentTime += Time.deltaTime;
yield return null;
}
}
Within 2 seconds, the object moves 10 units on the X axis. You can change those values as you like.
↧