- Home /
Asteroids in C#: Hyperspace (Teleport to random position)
Hi guys, a little new to Unity. I'm trying to remake Asteroids, and of course there is this ship's ability known as "hyperspace" which means it would teleport to a random place in the game scene when the user presses the shift key. So far, I have these lines of code in my Ship's script:
void Start(){
newXpos = Random.Range(minX, maxX);
newZpos = Random.Range (minZ, maxZ);
}
void Update(){
if(Input.GetKey (KeyCode.LeftShift)){
myTransform.position = new Vector3(newXpos, 0, newZpos);
}
}
The problem is that whenever I press shift, the ship would appear in several other places within a few frames, before settling in its new position. (I hope I described it well enough :( )Do you have ideas in which I could prevent it and just instantly place it in the new position?
Answer by robertbu · Oct 03, 2013 at 08:32 AM
You want Input.GetKeyDown(). GetKey() returns true for every frame the key is held down. Plus you need to recalculate your random positions each time the key is pressed:
void Update(){
if(Input.GetKeyDown (KeyCode.LeftShift)){
myTransform.position = new Vector3(Random.Range(minX, maxX), 0, Random.Range (minZ, maxZ));
}
}
Your answer