- Home /
Drag image and slow movement down after letting go?
Hi,
I am using the following script to drag a 2D image arround within a min and max position value (basically a map).
public void OnDrag(PointerEventData eventData)
{
transform.localPosition += (Vector3)eventData.delta * 2f;
}
void Update()
{
Vector3 currentPosition = transform.localPosition;
currentPosition.y = Mathf.Clamp(currentPosition.y, minY, maxY);
currentPosition.x = Mathf.Clamp(currentPosition.x, minX, maxX);
transform.localPosition = currentPosition;
}
I would like to not have the image come to a hard stop after letting go but smoothly slow it down over like 1 or 2 seconds. Any help how to achieve this is much appreciated.
Thanks in advance!
Answer by NPnpNPnpNP · Jan 25 at 10:20 PM
You can use Vector3.Lerp() to move the image, and combine it with an Animation Curve to adjust the speed over time.
Here a good example of how I achieve this kind of animations in my games :
public AnimationCurve animationCurve;
public void StartMove(Vector3 finalPosition)
{
StartCoroutine(Move(transform.position, finalPosition, 2));
}
private IEnumerator Move(Vector3 origin, Vector3 finalPosition, float duration)
{
for (float i = 0; i < duration; i += Time.deltaTime)
{
transform.position = Vector3.Lerp(origin, finalPosition, animationCurve.Evaluate(i / duration));
yield return null; // Returning null here allows to wait for the next update.
}
}
Thanks for your answer!
But i don't really get how that could work in my case... Wouldn't I need the "finalPosition" before i drag the map but it would change depending where and when I let go of the map...
Sorry my English is not perfect so I'm not sure that I understand what you're trying to do. Do you have a video to illustrate it ?
yeah, sure.
https://www.youtube.com/watch?v=hUtX-FX1IFU
So I have the red square as a placeholder for my map and I am dragging it around using the script I put in my question above. The thing I want to achieve is that after I let go of the mouse button (ending the dragging) I don't want the red square to stop immediately like it does in the video but I would like it to slow down slowly. Just like it does on Google Maps or Apple Maps for example.
Your answer
Follow this Question
Related Questions
Camera not moving 'smoothly' on drag. 2 Answers
[Solved] Move camera with mouse dragging (2D) 1 Answer
Assigning UV Map to model at runtime 0 Answers
Smooth material of cylinders 2 Answers
How can I make GUI labels Draggable? 2 Answers