Created
July 10, 2016 16:13
-
-
Save Streamweaver/29327ae77e890753f487f276cce48620 to your computer and use it in GitHub Desktop.
Question on Efficiency of position updates in unity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This is the working code. | |
// Aadvantage is simplicity and object is updated on intermediate states. | |
// Possible Disadvantage? I'm issuing updates to the game object transform every frame, | |
// but the only actual update I care about is the last one. | |
void Update () { | |
MoveShip (); | |
} | |
void MoveShip() { | |
if (Input.GetKey (KeyCode.RightArrow)) { | |
transform.position += Vector3.right * Time.deltaTime * speed; | |
} else if (Input.GetKey (KeyCode.LeftArrow)) { | |
transform.position += Vector3.left * Time.deltaTime * speed; | |
} | |
float newX = Mathf.Clamp (transform.position.x, xMin, xMax); | |
transform.position = new Vector3(newX, transform.position.y, transform.position.z); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Alternative to above for question. | |
// Advantage is I'm not issuing needless updates to the player object. | |
// Poissible Disadvantage is creating more objects than I need. | |
void Update () { | |
MoveShip (); | |
} | |
void MoveShip() { | |
Vector3 moveTo = new Vector3 (transform.position.x, transform.position.y, transform.position.z); | |
if (Input.GetKey (KeyCode.RightArrow)) { | |
moveTo += Vector3.right * Time.deltaTime * speed; | |
} else if (Input.GetKey (KeyCode.LeftArrow)) { | |
moveTo += Vector3.left * Time.deltaTime * speed; | |
} | |
float newX = Mathf.Clamp (moveTo.x, xMin, xMax); | |
transform.position = new Vector3(newX, moveTo.y, moveTo.z); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment