Hi am developing a simple Space Shooter styled 2D game and I am stuck at the point where the Object should restrict itself moving beyond the left and right edges of the screen.
I implemented @Waz solution in one of the answers in Unity Answers and it works great if the object is not a rigidbody. However if it is applied to a rigidbody, the object starts to flicker. Below is the code that I used from @Waz
float speed = 0.1f;
Vector3 viewPos = Camera.main.WorldToViewportPoint(transform.position);
viewPos.x = Mathf.Clamp01(viewPos.x);
viewPos.y = Mathf.Clamp01(viewPos.y);
transform.position = Camera.main.ViewportToWorldPoint(viewPos);
Here is the link where @Waz mentioned his piece of code: http://answers.unity3d.com/questions/148790/detecting-the-edge-of-the-screen.html
Here is a link that says to use an alternative solution for rigidbody but this code does not work for me: http://answers.unity3d.com/questions/62189/detect-edge-of-screen.html
I am not sure how to modify the above code so that the object I touch and move does not flicker. Any help would be great.
You are translating from arbitrary float coordinates to the range [0,1] and back again. Likely the issue you are running into is due to floating-point inaccuracies when your world-position is far away from 0.
There are multiple ways of solving this:
OnBecameVisible() and OnBecameInvisible() messages. Don't let the player move off screen if it would cause them to "go invisible".IsVisibleFrom() callback from this wiki article. Some people prefer this because they claim that "OnBecameVisible()/OnBecameInvisible() are broken."If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With