Move Object in Button Click smooth to position?
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).
public void Clicked()
{
Vector3 Picposition = Pic.transform.position;
Picposition.y -= 10f;
Pic.transform.position = Picposition;
}
Thx, Hollo1001
Answer by TreyH · Feb 12, 2016 at 07:20 PM
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.
Answer by wesleywh · Feb 12, 2016 at 04:45 PM
I would suggest looking into "Vector3.Lerp" here is the unity documentation about it:
http://docs.unity3d.com/ScriptReference/Vector3.Lerp.html
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.
EX:
this.transform.position
So here is a complete example that you could use:
transform.position = Vector3.Lerp(transform.position, target.position, speed * Time.deltaTime);
Your answer
Follow this Question
Related Questions
SmoothDamp bug? 0 Answers
Can't make smooth rotation using joystick 0 Answers
Need help with my code 0 Answers
lerp works on (-6.5/y/z) but not on (+6.5/y/z) 0 Answers
Why is this not moving? 1 Answer