Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity3D Detecting the Edge of the Screen - Object is Flickering when moved

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.

like image 203
Sriram Kumar Avatar asked Dec 01 '25 01:12

Sriram Kumar


1 Answers

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:

  1. In your above script, only perform the transform if they are actually touching the edge of the screen.
  2. Handle the OnBecameVisible() and OnBecameInvisible() messages. Don't let the player move off screen if it would cause them to "go invisible".
  3. Use the IsVisibleFrom() callback from this wiki article. Some people prefer this because they claim that "OnBecameVisible()/OnBecameInvisible() are broken."
    I don't know how/why they believe they're broken.
like image 114
BlueRaja - Danny Pflughoeft Avatar answered Dec 04 '25 19:12

BlueRaja - Danny Pflughoeft



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!