- Home /
Problem with while statement.
Hi, I have a physics based educational game that I am working on and I have a problem. I have a catapult that I should be able to move with the left and right arrow keys. Originally the player would have to keep pressing the keys in order to get it to continue moving but I have decided that for this, a while statement would be better than my original if. the problem was that as it is an update function, the while statement would push the catapult as far as it would allow in its conditions within a single frame. I wanted my catapult to move in increments when the keys are held. I decided to add a timer to split this up but it seemed ineffective.
here is my code:
var delayCount : float = 5.0f;
function Update() {
delayCount -= Time.deltaTime; if (delayCount<0) {
gameObject.tag == "catapult main";
while(Input.GetKeyDown ("left") && gameObject.transform.position.x > -10)
{
gameObject.transform.position.x -= 1;
}
while(Input.GetKeyDown ("right") && gameObject.transform.position.x < 10)
{
gameObject.transform.position.x += 0.001;
}
delayCount = 5.0f;
}
}
Answer by aldonaletto · Jan 04, 2012 at 04:01 PM
You should not use while or for loops inside Update unless they are limited counting loops (loop for 5 times, for instance), because they will lock your game until the condition is satisfied. You could move smoothly using this:
var speed : float = 5.0f; // meters per second
function Update() { // why are you changing the tag inside Update? gameObject.tag == "catapult main"; // move this object at constant velocity = speed: if (Input.GetKey ("left") && transform.position.x > -10){ transform.position.x -= speed Time.deltaTime; } if (Input.GetKey ("right") && transform.position.x < 10){ transform.position.x += speed Time.deltaTime; } }
Thanks for the reply :)
I have tried this and it seems to do the same as my previous if statements. The problem is that the catapult will only move once for each key press. What I am looking for is a way to get the catapult to continue moving for each second or so that the key is pressed down.
I read your question too fast, and made the same mistake: you should use Get$$anonymous$$ey ins$$anonymous$$d of Get$$anonymous$$eyDown - Get$$anonymous$$eyDown returns true only during the current Update, while Get$$anonymous$$ey returns true while the key is pressed (answer edited to use Get$$anonymous$$ey).
thankyou, that has done it :)
I really appreciate your help, from what I've seen, you are a big help on this forum.
Your answer
Follow this Question
Related Questions
Increment in while loop, with timeout 1 Answer
What part of my While Loop is causing the game to freeze? (C#) 2 Answers
Is there a way to have an object gradually move to one spot, move back, and then stop? 1 Answer
Breaking from a Loop 2 Answers
While Loop won't end when SendMessage was executed.. 2 Answers