aresz
aresz

Reputation: 2649

Make rigid body bounce off the screen edge

I'm currently working on an object that involves bubble-like movement. This object has a rigidbody and a sphere collider.

I use the AddForce method every 1-3 seconds to make it move continuously and slowly.

Now I'd like to know how to make the rigidbody move in the opposite direction (a.k.a bounce off) when they reach the screen edge already. I have already computed the screen edges using ViewportToWorldPoint method.

One ineffective solution that I thought of is to put empty game objects with collider at the edges but that won't work in my case since I'm building for mobile devices which have different screen resolutions/sizes.

Anyone know a good solution for this?

Upvotes: 2

Views: 2915

Answers (2)

NeverHopeless
NeverHopeless

Reputation: 11233

In order to get a reflection effect, you need Material. Attach a bouncy material to the edges(gameObject) and let the physics calculate what should be the reaction of collision.

Create a Physics 2D material and set the bounceness to some appropriate value say 0.2.

Regarding your issue:

One ineffective solution that I thought of is to put empty game objects with collider at the edges but that won't work in my case since I'm building for mobile devices which have different screen resolutions/sizes.

If you are working with UI component then dealing with boundaries should not be a problem (since it anchors with different resolution) but if it is not the case you can create a script CameraResizer and an enum Anchor (Left, Right, Top, Bottom) and using the same way ViewportToWorldPoint you can align your empty gameObject (boundary) to any screen size by attaching it the gameObject.

Hope it helps!

Upvotes: 2

Vitor Figueredo
Vitor Figueredo

Reputation: 629

I'm not sure i got the idea. But i think i had the same problem when i was writing an old mobile game.

I had the same idea you did, use empty game objects with box collider on the edges, but then i thought, this isn't responsive, so i wrote this code:

public class Walls_c : MonoBehaviour {

    public Transform righttop;
    public Transform rightbottom;
    public Transform lefttop;
    public Transform leftbottom;

    // Use this for initialization
    void Start () {
        righttop.transform.position = Camera.main.ViewportToWorldPoint(new Vector3(1,1,0));
        rightbottom.transform.position = Camera.main.ViewportToWorldPoint(new Vector3(1,0,0));
        lefttop.transform.position = Camera.main.ViewportToWorldPoint(new Vector3(0,1,0));
        leftbottom.transform.position = Camera.main.ViewportToWorldPoint(new Vector3(0,0,0));   
    }
}

With this, i always get the corners of the screen. It's no fancy... but it works.

Let me now if it works.

Upvotes: 3

Related Questions