Bonus: Laser Offset — Dynamic Offset Evaluation
Objective: Dinamically set the offset for laser instantiation position
In the laser instantiation article, we managed to shoot laser pulses (capsules) from the ship (square), but a keen eye could tell that the lasers ugly originate from the centre of the square. It would be very cool if the lasers could start from the tip of the ship!
In order to do so, we should just modify the Vector3 indicating the position in which the lasers are instantiated.
But how? Should we add an offset to the y-component? How big? Should we try different values until we get what we like? No.
Let’s think: transform.position is the position of the ship sprite. If we look at the Inspector, we can find that this position, the Sprite Sort Point, is nothing less that the centre of the sprite (it could be changed but it is OK like this).
So, in order to have lasers coming from the top, the new position should be the old one (the centre) plus half the vertical size of the sprite. Once we make it work, we could forget about the actual size of the ship or even about it changing during the game because the position would then be calculated along this changes!
The only problem to solve is just how to evaluate the sprite actual world size.
Here is how I managed to do it. It may seem complicated, but actually it is not. Let’s look into it.
First, let’s declare new variables we need: the new position and a sprite renderer, holding all sprite information.
Get the sprite renderer component of the player at the begin.
Now let’s store the old position in the new private variable. We need it because the new one is just the old plus an offset added to the y-component.
The offset is quite engaging, we:
- Get the image size of the sprite, in terms of pixels, from the sprite renderer object
- Divide it by two, obviously
- Divide it by the ratio pixelsPerUnit (how many pixels in one game-world space unit)
- Multiply by the scale (the one you can see in transform component).
These four steps will lead you from a pixel size of the image, to the world size for the sprite object, corrected by the scale you chose.
… and that’s it!