I have a very simple script written to allow player to wrap around the screen on the X axis when Q is held down but Y should always be clamped. What I cannot get my head around is how in the below code Y is not getting clamped while Q is held down. Y is however getting clamped properly if Q is not held down. Code (CSharp): //Move player based on axis input transform.Translate(new Vector3(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"), 0) * Time.deltaTime * speed); //If Q is held down allow horizontal wrapping if (Input.GetKey(KeyCode.Q) && transform.position.x < -11.2f) { transform.position = new Vector3(11.2f, Mathf.Clamp(transform.position.y, -3.8f, 0), 0); } else if (Input.GetKey(KeyCode.Q) && transform.position.x > 11.2f) { transform.position = new Vector3(-11.2f, Mathf.Clamp(transform.position.y, -3.8f, 0), 0); } if(!Input.GetKey(KeyCode.Q) && transform.position.x > -11.2f & transform.position.x < 11.2f) transform.position = new Vector3(Mathf.Clamp(transform.position.x, -9f, 9f), Mathf.Clamp(transform.position.y, -3.8f, 0), 0);
You code will only clamp y if transform.position.x < -11.2f or transform.position.x > 11.2f because you are AND-ing those conditions to the first set of if/else statements. Overasll your logic here is very convoluted. I suggest simplifying the whole thing: Code (CSharp): //Move player based on axis input Vector3 newPosition = transform.position + new Vector3(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"), 0) * Time.deltaTime * speed); // always clamp y: newPosition.y = Mathf.Clamp(newPosition.y, -3.8f, 0f); // Always set z to 0 newPosition.z = 0; // Wrap X if Q is held down: bool wrapX = Input.GetKey(KeyCode.Q); if (wrapX) { if (newPosition.x < -11.2f) { newPosition.x = 11.2f; } else if (newPosition.x > 11.2f) { newPosition.x = -11.2f; } } // If Q is not held down, clamp X between -9 and 9 else { newPosition.x = Mathf.Clamp(newPosition.x, -9f, 9f); } transform.position = newPosition;