- Home /
move texture 2d with Time.deltatime
I want to move a texture 2d on touch end. currently I have functionality of setting the texture 2d to the center on Touch end. i want it to be look smoothly come to the center. I am using this script to do so. my texture2d's y position is stored in padYpos. this is in OnGUI( )
if((Input.GetTouch(0).phase==TouchPhase.Ended) || (Input.GetTouch(0).phase==TouchPhase.Canceled))
{
if(dist>0f)
{
while (padYpos>center.y)
{
padYpos+=Time.deltaTime*5f;
dist=center.y-padYpos;
}
}
if(dist<0f)
{
while (padYpos<center.y)
{
padYpos-=Time.deltaTime*10f;
dist=center.y-padYpos;
}
}
}
GUI.DrawTexture(new Rect(padXpos, padYpos, padWidth, padHeight), pad);
Answer by hirenkacha · Jun 11, 2012 at 05:25 AM
I found the solution. I am not using while loop now as told by Walframe. So I am using the code in simple update ().
if(dist>0f)
{
padYpos+=Time.deltaTime*5f;
}
else
{
padYpos-=Time.deltaTime*5f;
}
Answer by Berenger · May 14, 2012 at 05:48 AM
You shouldn't use Input in OnGUI. Put it in Update instead. Then, you can start a coroutine on touch that will interpolate dist minVal to maxVal in x seconds. The GUI.DrawTexture, however, must stay in OnGUI.
ok... so i shld use all calculations in Update(). But is my logic correct..???
I have put Input and all the calculation in Update function but its still not working any idea y???
I am not familiar with touch methods, but I guess Ended and Canceled are ponctual. Then, your code will only be executed once. That's why the movement shouldn't happen here but inside a coroutine started there.
Answer by Wolfram · May 14, 2012 at 02:22 PM
Apart from what Bérenger said, you cannot use/see changes to your scene done in a simple while loop, since it will never render the scene while inside the loop. Update() (and OnGUI()) are called exactly ONCE per frame, so your scene will appear to be stuck while the loop is fully executed, and there will be no updates inbetween.
As Bérenger suggests, use Update(), launch a Coroutine instead of putting the while-loop directly in Update(). But then move each while-loop to a Coroutine, with "yield return 1;" (in C#) being the last statement within the loop.
Your answer
![](https://koobas.hobune.stream/wayback/20220613071443im_/https://answers.unity.com/themes/thub/images/avi.jpg)