I want to move an Object from one to a other position smoothly and with defined speed.
Whit this code i only can set the position to that i want. But how can i moth it multiple times and smooth(over time).
By the nature of your function name (Clicked: past tense, singular), you want a single process to be started and manage itself from the time of your click. The way to accomplish this is a Coroutine.
void Clicked()
{
// Get the target position
Vector3 relativeLocation = new Vector3(0, -10, 0);
Vector3 targetLocation = Pic.transform.position + relativeLocation;
float timeDelta = 0.05f;
// Start your coroutine
this.StartCoroutine(SmoothMove(targetLocation, timeDelta));
}
IEnumerator SmoothMove(Vector3 target, float delta)
{
// Will need to perform some of this process and yield until next frames
float closeEnough = 0.2f;
float distance = (Pic.transform.position - target).magnitude;
// GC will trigger unless we define this ahead of time
WaitForEndOfFrame wait = new WaitForEndOfFrame();
// Continue until we're there
while(distance >= closeEnough)
{
// Confirm that it's moving
Debug.Log("Executing Movement");
// Move a bit then wait until next frame
transform.position = Vector3.Slerp(Pic.transform.position, target, delta);
yield return wait;
// Check if we should repeat
distance = (Pic.transform.position - target).magnitude;
}
// Complete the motion to prevent negligible sliding
Pic.transform.position = target;
// Confirm it's ended
Debug.Log ("Movement Complete");
}
edit: Changed transform.position to Pic.transform.position, as poster had.
I would suggest looking into “Vector3.Lerp” here is the unity documentation about it:
Here is how you would use it:
transform.position = Vector3.Lerp(<FROM_POSITION>, <TO_POSITION>, <CALC_DISTANCE>);
Inside <CALC_DISTANCE> this variable could account for your speed or a distance variable like they do in the example.
The example they provide is amazing. Click on the link and check it out. The Vector3.Lerp will smoothly transition from one point to another just like you want. This would most likely be called on an update function and have the “” be the current position of the person you are moving.