Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Streamweaver/29327ae77e890753f487f276cce48620 to your computer and use it in GitHub Desktop.
Save Streamweaver/29327ae77e890753f487f276cce48620 to your computer and use it in GitHub Desktop.
Question on Efficiency of position updates in unity
// 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);
}
// 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