Ditto
Ditto

Reputation: 296

Using a container object as a mask

This is a 2D Game.

I'm trying to move an object which is within another object an make it disappear once it's out of the container object boundaries (just like in web development a div with attribute overflow set to hidden).

NOTE: I can move the object, that's not the issue. But I cannot make the parent object behave as a container.

See snippet for clarification.

.blue {
  width: 400px;
  height: 400px;
  background: blue;
  position: relative;
}

.red {
  width: 200px;
  height: 70px;
  background: red;
  position: relative;
  left: 50px;
  top: 50px;
  overflow: hidden;
}

.yellow {
  width: 20px;
  height: 20px;
  background: yellow;
  position: relative;
  left: 75px;
  top: 20px;
}
<div class="blue">
  <div class="red">
    <div class="yellow"></div>
  </div>
</div>

The blue square represents the scene. The red rectangle is the container object. The yellow square is a nested object. What I'm trying to achieve is this: move up the yellow square until it gets out of sight by not being inside the visible area of the red rectangle anymore.

Unfortunately, despite being nested in the red rectangle object, the yellow square object is still visible in the scene (blue square) whenever I move it up.

I'm a total JR in unity and I know this question is monumentally silly, but I haven't found (or at least that's what I think) an answer regarding how to tackle this.

Upvotes: 1

Views: 142

Answers (3)

Sai Nadh
Sai Nadh

Reputation: 101

If it is 2D use sprite mask. If in 3D I Think you can achieve this if you use multiple cameras. Create another camera which renders only red and yellow square. And adjust camera size to Red sqaure.

Upvotes: 1

Nathalia Soragge
Nathalia Soragge

Reputation: 1435

I think Sprite Masks are what you're looking for.

Here is the manual of how to use them:

Sprite Masks

Upvotes: 1

Michal Varyš
Michal Varyš

Reputation: 142

Hello did you try Collider2D? Colliders have function isTouching so you can actually check whether the yellow box is inside the red one or not. if they don't touch, you can make it disappear by disabling renderer

gameobject.getCompponent<Renderer>().enabled = false;

here is the reference to the method: https://docs.unity3d.com/ScriptReference/Collider2D.IsTouching.html

Upvotes: 0

Related Questions