- Home /
Problems with Clamping Player to Screen
I am currently working on a simple Space Shooter. To clamp my space ship to the screen I use this code snippet:
ScreenPosition = Camera.main.WorldToViewportPoint (this.transform.position);
ScreenPosition.x = Mathf.Clamp(ScreenPosition.x,0f, 1f);
ScreenPosition.y = Mathf.Clamp(ScreenPosition.y, 0f, 1f);
this.transform.position = Camera.main.ViewportToWorldPoint(ScreenPosition);
But the space ship is invisible when I start the game. It is still shooting, but the ship and its children are not visible. If I delete the last line, everything is fine, except that the ship isn't clamped to the screen anymore. I can't figure out how to work around this problem.
edit: I am not getting any errors in the console.
Thanks in advance...
Answer by BugFighter · Jul 25, 2015 at 03:53 PM
I was playing around with the code and found the answer myself, so if anyone ever has a similar problem, this is how I solved it. At first, my ScreenPosition variable was a Vector2 variable. As soon as I changed it to a Vector3 and added the transform.position.z from the Prefab as ScreenPosition.z (which was 5):
ScreenPosition = Camera.main.WorldToViewportPoint (this.transform.position);
ScreenPosition.x = Mathf.Clamp(ScreenPosition.x,0.07f, 0.93f);
ScreenPosition.y = Mathf.Clamp(ScreenPosition.y, 0.07f, 0.93f);
ScreenPosition.z = 5f;
this.transform.position = Camera.main.ViewportToWorldPoint(ScreenPosition);
the spaceship didn't disappear anymore. Before, the position of the spaceship was changed to 0 and probably rendered behind the camera or something like that.
Your answer
Follow this Question
Related Questions
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
How to make Line Renderer lines stay flat? 2 Answers
How to swap sprites? 1 Answer
2D Collision problem 1 Answer