# Unity - Play animation based on horizontal drag position

What I want to do is somewhat complicated, but I'll try to explain it to the best of my ability. I am using Unity's EventSystems events to detect a drag. When the user drags the object horizontally, I want to play the animation relative to the position of the object.

For example: If the user drags object to position 0.5, I want the animation to only play to time 0.5, and if the user drags back to 0.2, I want the animation to play back to time 0.2

Currently, I do not have any code because I do not know where to begin.

• This looks similar to a previous question about seeking animation using x position — did you check that one out to see if its answer helped you? If it didn't, can you edit your post to explain where it went wrong or where you're still stuck? Mar 20, 2019 at 11:59

Due to the luck of more detailed information I’ll have to do some assumptions. I’m not sure to understand exactly what you mean by “only play to time 0.X”, so I’ll assume you mean that you have one animation clip and you want to set the frame based on the position. Since you did not specify the direction I’ll assume you mean to do it in a 2d space along the X axis. I will consider as if you’ll be using C#.

An animation clip goes from 0 (start) to 1 (end) so you need to normalize the position of your gameObject in order to set the value of animation. Say your object can only be moved between -5 < X < 7 than you would need to normalize this space like so:

float normalizedPosX = (yourObj.position.x + 5) / 12;


Now that you have your position returned as a value between 0 and 1 than you can set your clip to play at the given time. You can do this in different ways depending on the way you’re animating the object, I’ll assume you are using an Animator and will do that by using the following method:

animator.Play(“animationName”, 0, normalizedPosX);


It’s important to set the animation speed to 0 to avoid issues.

I hope this can be of help