- Home /
Problem moving a Rect
I have this simple code to move a Rect. My problem is that when I click/touch screen the Rect moves faster.
void OnGUI ()
{
if(i<=slideVel)
{
i++;
GUI.DrawTexture (new Rect ((-Screen.width/slideVel)*i, 0, Screen.width*2, Screen.height), texture);
}
else
{
GUI.DrawTexture (new Rect (-Screen.width, 0, Screen.width*2, Screen.height), texture);
}
}
I try to move this rect based on time but the problem is the same.
Somebody can help me?
Answer by fafase · Mar 24, 2014 at 11:19 AM
This is to be expected, you have a value and each round you are multiplying it by a greater value, the result is not constant.
Let's try and clean up a little:
Rect rect;
bool movement = false;
public float speed = 2f;
void Start()
{
// rect is calcuated only once
// your game won't make a significant jump but why not
rect = new Rect ((-Screen.width/slideVel), 0, Screen.width*2, Screen.height);
}
void Update()
{
// When pressing space rect will start moving
if(Input.GetKeyDown(KeyCode.Space))movement = true;
}
void OnGUI ()
{
if(movement){
if(rect.x < xPos) // This could also be replaced with a Mathf.Clamp
rect.x += speed * Time.deltaTime;
}
GUI.DrawTexture (rect, 0, Screen.width*2, Screen.height), texture);
}
I would guess that should do it.
thx but the problem persist. GUI.DrawTexture (new Rect (0, 0, Screen.width*2, Screen.height), texture); is start position
GUI.DrawTexture (new Rect (-Screen.width, 0, Screen.width*2, Screen.height), texture); is final position.
If I'm clicking on the screen this rect is moving faster. With my code, your code and other code that I already try the problem is the same :|
It is true, I think it is an issue related to OnGUI that is called more times than normal
Yes, OnGUI() gets called multiple times per frame (and the number of times varies with the number of events. Given the code there, the easiest thing to do would be to move lines 17-20 into Update(). You could leave it in OnGUI() and only increment it on a repaint event.
@fafase - the problem with making speed smaller is that you don't get a fixed number of events. The number of events varies. For example, you only get a keydown event if the user presses a key. I believe you get just one repaint event per frame, so you could do this:
if (movement && Event.current.type == EventType.Repaint)
Your answer
![](https://koobas.hobune.stream/wayback/20220613141033im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
texCoords rect for GUI.DrawTextureWithTexCoords 3 Answers
Scale Car Speedometer with Screen Size (made by Andeeee) 1 Answer
Help with destroying guiRect? 0 Answers
Can't destroy an ui element 2 Answers