Giulio Ladu
Giulio Ladu

Reputation: 192

Best way to line up Background sprite to camera viewport

I am new to Unity and experimenting with a basic game however I have hit a wall. I am trying to solve the following problem:

I have a long sprite which I would like to be able to load into a Game Object as part of a level loading script. The loading function creates a new game object, adds a sprite renderer and then adds the sprite. This all works OK assuming the background sprites are the same size (specifically height) however this approach falls apart when the background sprites are slightly different heights.

To fix this issue I was thinking of loading up the sprite to the renderer and then calculating the center of the sprite. Calculating the center of the orthographic camera view and then using the sprite transform to match both centers. something like this:

Calculate centers

Using those center points I should be able to use the SpriteRenderer's transform of the background sprite to align it to the camera center point.

Aligned

I guess only using background images which are the same size, would be the optimum solution here, however as I am experimenting ideally I would like to learn how this could work.

Is there a better solution?

Thank you

Upvotes: 0

Views: 159

Answers (1)

Prajwal Nagpure
Prajwal Nagpure

Reputation: 152

If you only want to use image for slide may be, then consider using UI canvas instead.

Step 1. setup image in scene view and make a prefab out of it. Step 2. spawn image (prefab) when required.

to fit the height set anchor as following (hold shift while selecting): https://i.sstatic.net/Hlo2J.png

Note 1 : make sure that you spawn image inside GameObject containing canvas component.

Upvotes: 1

Related Questions