I have a capsule which is my character and i need my capsule to spawn a sphere that will smoothly move to positions i set. There is code but it moves my character and i dont know how to spawn object in position of character and move it to another position
private void Start()
{
StartCoroutine(PingPongWithDelay());
}
private IEnumerator MoveFromTo(Vector3 startPosition, Vector3 endPosition, float time)
{
var currentTime = 0f;
while (currentTime < time)
{
transform.position = Vector3.Lerp(startPosition, endPosition, 1 - (time - currentTime) / time);
currentTime = Time.deltaTime;
yield return null;
}
transform.position = endPosition;
}
private IEnumerator PingPongWithDelay()
{
while (true)
{
yield return MoveFromTo(new Vector3(0f, 0f, 0f), new Vector3(0f, 0f, 1f), 2f);
yield return new WaitForSeconds(1f);
yield return MoveFromTo(new Vector3(0f, 0f, 1f), new Vector3(0f, 0f, 0f), 2f);
yield return new WaitForSeconds(1f);
}
}
}
CodePudding user response:
As said you already have your template routines you just have to use them like you want e.g.
public void SpawnSphere(Vector3 startPosition, Vector3 targetPosition, float duration)
{
var sphere = Instantiate(spherePrefab);
StartCorouine (MoveFromTo(sphere.transform, startPosition, targetPosition, duration);
}
private IEnumerator MoveFromTo(Transform obj, Vector3 startPosition, Vector3 endPosition, float time)
{
obj.position = startPosition;
for (var timePassed = 0f; timePassed < time; timePassed = Time.deltaTime)
{
obj.position = Vector3.Lerp(startPosition, endPosition, timePassed / time);
yield return null;
}
obj.position = endPosition;
}