Making Effects That Travel Between the 2D and 3D Worlds in Unity

I'm Hirayama from the Technology Department, and in this article I'll write about how to send effects back and forth between characters in the 3D world and the 2D UI pinned to the top and bottom edges of the screen, as in the video above.
I've put a runnable sample on the web, so feel free to try it out. Dragging moves the camera, and tapping or pressing a key spawns an effect. Notice that even if you move the camera after an effect appears, it still flies to the right place. The code is on GitHub too.
Even in games that render in 3D, it's common to display information on 2D layers drawn on top. Our Tokyo Prison, for example, takes that approach.

In games like this, you sometimes want visuals that travel between 3D and 2D.
For example, a character might use a skill, and as a result points shown in 2D go up, a gauge fills, or a skill card changes state. But if these are shown separately, it's hard to see the link between cause and effect. So you send something flying from the character toward the 2D element: the gauge, number or card. Moving things catch the eye, and the direction of motion makes the cause-and-effect relationship intuitive. Tokyo Prison has a mechanic along the lines of "using skills fills your special move gauge," and we use this effect to show it.
Conversely, if tapping a 2D UI element makes something happen to a character, you may want to send something flying from the UI element toward the character. In Tokyo Prison, for example, when a character is knocked out, a fireball flies toward the "KO counter" at the top of the screen, and money and treasure chests pop out of defeated enemies and fly to the money and treasure chest counters at the top of the screen.
People can usually follow only one moving thing at a time, so don't overdo it, but used well, I think it can make things easier to understand.
So how do you implement effects like these?
Put everything in the 3D world
Conceptually, the simplest approach is to put everything in the 3D world. The 3D world is fixed in world coordinates, and you decide, for example, that "the battlefield spans X from -100 to 100 and Z from -20 to 20." Then you treat the 2D UI as if it were placed in the same 3D world, and reposition it every frame so it stays at a fixed position relative to the camera. If the camera moves up 1 m, you move the UI up 1 m too. That way it appears to stay still. When you look out from inside a car, a sticker on the window doesn't seem to move, but it's actually moving along with the car and everyone inside.
With this approach you need only one camera, so you don't waste performance on multiple cameras. Everything lives in the 3D world, so if things travel back and forth often, this is the simplest option. You can also do any 3D-style presentation you like, such as tilting the UI relative to the camera for a sense of depth, or moving it along the depth axis. It's a good way to make a UI that stands out a bit.
However, going that far means building the entire UI out of SpriteRenderers, so you miss out on UnityEngine.UI's handy features. Not being able to place images pixel by pixel would be quite inconvenient, and sometimes you won't want to go that far. In that case, you can build the UI with UnityEngine.UI and simply place the Canvas in world space. If you make the canvas a child of the camera, its relative position is maintained, so it doesn't add much work either.
But for Tokyo Prison, we didn't go with this method. We had already built the game with separate cameras for 3D and 2D, and changing that after the fact would have been a hassle. Also, with separate cameras you don't have to worry about 3D elements covering 2D elements, and it's easy to split UI elements across several scenes, because there's no need to put the Canvas under the camera. Having every scene "read the camera's coordinates and reposition itself correctly every frame" would be a pain, too.
Keep the 2D and 3D worlds separate
So in Tokyo Prison, we decided to keep the cameras separate. There are two main ways to do this.
- Put the thing you send flying in the 3D world
- Put the thing you send flying in the 2D world
In the first case, you build the flying object with a SpriteRenderer or MeshRenderer, place it in the 3D world's coordinate system, and render it with the 3D camera. Then, if you want it to look as though it started from a 2D element, for example, you calculate "where the 2D element would be if it were in the 3D world." You then start from those coordinates and move the object in the 3D world's coordinate system. Since it's drawn by the 3D camera, which is a Perspective camera, you don't need to worry about perspective. As it moves away, it gets smaller on its own.
In the second case, you build the flying object with UnityEngine.UI and render it with the 2D camera. The UI is laid out in a 2D coordinate system, and moving it as is wouldn't blend in with the 3D world, so again you calculate "where the 2D element would be if it were in the 3D world" and move it in the 3D world's coordinate system. Then you calculate "where those 3D world coordinates would appear from the 2D camera's point of view," and from that, the values to put in the Transform. On top of that, you adjust the scale based on the distance from the camera, implementing "smaller the farther away" by hand. That's because the 2D camera uses orthographic projection (Orthographic), so things don't shrink as they move away. This is much more of a pain, but you need it if you want to control the drawing order relative to UI elements.
Tokyo Prison uses only the second approach, but I've implemented both for this sample.
First, the structure of the sample
Before getting into the details, let me briefly go over how the sample is structured.
The scene's object tree looks like this.

The scene, called Sample, contains objects called 3D and 2D. Under 3D is Camera3D, which renders the stage, the characters and the "effects placed in the 3D world." Under 2D is Camera2D, which renders the Canvas and the "effects placed in the 2D world." To keep 3D objects out of the 2D camera's view and 2D objects out of the 3D camera's view, the 2D world's camera is offset by about 100 in Z.

The only script is the Sample class attached to the MainScript object. All the code shown from here on comes from it.
Placing 3D things to match 2D
In the sample, the effects that fly from the UI to the characters live in the 3D world. The coins and boxes at the top of the screen, and the round thing labeled "Burst" at the bottom, are UI, and the effects fly from there toward the characters.
The code that does this is Sample.UpdateEffect3D(), and roughly speaking it does the following.
- Get the coordinates in the 3D world of the UI at the starting point
- Interpolate between the starting point and the target point
- Set the world coordinates on the effect's Transform
Let's look at them one at a time.
Getting the UI's coordinates in the 3D world
The code that does this is Sample.Calc3dWorldPositionOfUi.
static void Calc3dWorldPositionOfUi(
out Vector3 worldPositionOut,
Transform uiTransform,
Camera camera2d,
Camera camera3d,
float uiPlaneDistanceFromCamera)
{
var worldPos2d = uiTransform.position; // Get the world coordinates in the 2D world
var screenPos = camera2d.WorldToScreenPoint(worldPos2d); // Convert to screen coordinates
var cosine = Vector3.Dot(ray.direction, camera3d.transform.forward)
/ camera3d.transform.forward.magnitude; // ray.direction always has length 1, so no need to divide by it
var distance = uiPlaneDistanceFromCamera / cosine;
worldPositionOut = camera3d.transform.position + (ray.direction * distance);
}
Step by step, it does this:
- Get the world coordinates in the 2D world of the UI at the starting point
- Get their screen coordinates
- Convert these screen coordinates into a ray in the 3D world
- Pick one point on the ray
Getting world coordinates in the 2D world
You can get them with Transform.position.
World coordinates in the 2D world → screen coordinates
Screen coordinates are what link the 2D camera and the 3D camera. Whenever you cross between cameras, you generally go through screen coordinates. The calculation goes in this order: "it appears here on the screen through the 2D camera; something that appears at that spot through the 3D camera has these world coordinates in the 3D world." You use Camera.WorldToScreenPoint().
Both 2D and 3D objects have world coordinates, but world coordinates in the 2D world are merely coordinates that show up conveniently in the 2D camera, and can't be used when looking through the 3D camera. Remember that the 2D camera is offset by Z+100. So even when talking about world coordinates, I'll qualify them with "in the 2D world" or "in the 3D world" (with a single camera, you wouldn't have this complication).
Screen coordinates → a ray in the 3D world's world coordinate system
To convert screen coordinates to world coordinates, you first go through a ray. That's because "a point on the screen" is actually not a point but a straight line. If you hold a straight stick right in front of your eye, pointing straight ahead, it looks like a point. Where on that line the point lies, or how far it is from the camera, is undetermined. You have to decide that yourself.
For this you can use Camera.ScreenPointToRay(). Be careful which camera you use. Use the 3D camera and you get "a ray in the 3D world's world coordinate system"; use the 2D camera and you get "a ray in the 2D world's world coordinate system."
A ray in the 3D world's world coordinate system → world coordinates in the 3D world
In this sample, a variable called uiPlaneDistanceFromCamera determines this, and you can adjust it at runtime from the sample's GUI. It represents "how far from the camera the plane that the coins, boxes and Burst circle sit on would be, if it were in the 3D world." Note that it's not "the distance to the UI" but "the distance to the plane the UI sits on."
ray.direction is the vector from the camera toward the UI element, and the UI element we're looking for lies along this vector, extended out from the camera.

The vector for the direction the camera faces is Camera.transform.forward. The distance to the plane the UI sits on is the uiPlaneDistanceFromCamera mentioned above. What we want to know is how far to extend ray.direction to reach the UI element, so the distance between the "UI element" and the "camera" in the diagram is what matters.
You can find it if you know the cosine of the angle (θ) between ray.direction and camera3d.transform.forward.
distance * cosine = uiPlaneDistanceFromCamera
That's the relationship. For the angle between two vectors A and B, the dot product gives us
cosine = Vector3.Dot(A, B) / (A.magnitude * B.magnitude)
so we can work it out from that. Here, the official manual says "Ray.direction has length 1", so we only need to divide by the length of camera3d.transform.forward, and
var cosine = Vector3.Dot(ray.direction, camera3d.transform.forward)
/ camera3d.transform.forward.magnitude; // ray.direction always has length 1, so no need to divide by it
var distance = uiPlaneDistanceFromCamera / cosine;
gives us the distance. Then just scale ray.direction by this length and add it to the camera position.
worldPositionOut = camera3d.transform.position + (ray.direction * distance);
Interpolation
Next, interpolate the coordinates.
Vector3 pos;
pos = Vector3.Lerp(srcWorldPos, dstWorldPos, t);
The sample code branches on a variable called _useBezier, but just look at the else branch.
It linearly interpolates between the starting point and the target point with Lerp, so the effect always arrives in the specified time, no matter what. If you want it to take longer the farther it has to go, you need a different calculation, and a fairly tedious one at that. For most purposes, interpolation that always arrives in the specified time is easier.
The interpolation factor t needs to be between 0 and 1, so it's calculated like this.
var t = effect.time / _effectDuration;
Dividing the seconds since the effect appeared (effect.time) by its display duration (effectDuration) gives a value from 0 to 1.
By the way, when _useBezier is true, it does a Bézier calculation to produce an arcing trajectory. It creates a control point by raising the midpoint between the starting point and the target point by about 5 m, and uses that to build the trajectory. It looks nicer than flying in a straight line, and Tokyo Prison does it this way too. Also, since I wanted a sense of acceleration, I square t, which makes the start slow and speeds up the second half. Ideally the parameters would be exposed for tuning, but "square it if you want acceleration" is a simple trick that works surprisingly well, so give it a try if you get the chance.
Setting it on the Transform
Then you just plug the resulting coordinates into the effect's Transform.position. If all the Transforms above the effect's GameObject are at their default values (position and rotation 0, scale 1), I suspect changing localPosition gives the same result faster than changing position, but I haven't verified it. The sample sets position, playing it safe.
Placing 2D things as if in 3D
Now for the main event: "the tedious one." If you treat the UI as sitting in front of the 3D world, it's actually easier to make the flying object 3D and use the approach above, and that's good enough. But if you "want it to look as though the UI is behind the 3D world," that won't do.
Take Tokyo Prison's "send things from defeated enemies to the coin count at the top of the screen" effect: I want the motion to look as though the top UI is farther back than the enemies, yet I want the effect drawn in front of the UI. In that case, it has to be drawn in the 2D layer. In Unity, adding cameras carelessly hurts performance, so I don't want to add a camera just to change the drawing order.
Let's look at how it works. In the sample, the "effects flying from characters to the UI" are implemented this way. The relevant code is around Sample.UpdateEffect2D(), and roughly it does the following.
- Get the coordinates in the 3D world of the UI at the target point
- Interpolate between the starting point and the target point
- Interpolate
- Convert the interpolated world coordinates in the 3D world into screen coordinates
- Convert the screen coordinates into a ray in the 2D world's world coordinate system
- Set the ray's origin as the effect's position.
- Find the "distance in the Z direction" from the camera.
- Calculate the scale from the distance
- Set the scale
Up to the interpolation, it's the same as before, but the resulting world coordinates in the 3D world then have to be carried over into the 2D world. That's the horribly tedious part. I'll explain from the point where interpolation is done.
Turning world coordinates in the 3D world into screen coordinates
Screen coordinates are what link 2D and 3D, so let's convert to screen coordinates first. The camera to use is the 3D camera. Use the wrong camera and it won't work.
Converting screen coordinates into a ray in the 2D world's world coordinate system
Screen coordinates can be converted into a ray with Camera.ScreenPointToRay(). The camera to use is the 2D one. This gives the world coordinates in the 2D world.
Using the ray's origin as the world coordinates
The 2D camera uses orthographic projection (Orthographic), so the ray.direction you get from ScreenPointToRay() is always (0,0,1). Feel free to verify this. In other words, whichever point you pick on the ray, x and y stay the same, and so does the position on screen. So the simplest option is to use Ray.origin. Set this as the effect's Transform.position. The code for this part looks like this.
var screenPos = _camera3d.WorldToScreenPoint(pos);
ray = _camera2d.ScreenPointToRay(screenPos);
effect.transform.position = ray.origin;
Doing perspective yourself
In 2D (orthographic projection), things don't automatically get smaller as they move away. If you want them to look as though they're in the 3D world, you have to do this scaling by hand.
Now, about calculating the scale: in ordinary 3D rendering, the scale is determined by the "distance in the Z direction" from the camera. Not the ordinary distance. Only Z matters. For example, if the camera is at (0,0,0), the distance to (80,90,100) is a little over 150, but the "z-direction distance" we care about is 100. We ignore x and y.
So you need to convert the effect's world coordinates in the 3D world into the view coordinate system (= the camera's local coordinate system) and look at the z value. Code along these lines does the job.
var posInViewSpace = _camera3d.transform.worldToLocalMatrix.MultiplyPoint(worldPosIn3d);
var zDistance = posInViewSpaec.z;
The 3D camera's Transform has a worldToLocalMatrix, so you transform the world coordinates with it, and the resulting z is the z-direction distance.
But there's an easier way to get it, without the suspiciously slow-looking business of fetching a matrix and multiplying a vector by it every time. Let's look at the diagram.

This time, we know where the UI element is, so we can calculate the distance between the camera and the UI element. What we want is the distance between the UI plane and the camera, in other words, the length of the line labeled camera.transform.forward. As before, we can get it once we know the cosine.
var camToPos = pos - _camera3d.transform.position;
var cosine = Vector3.Dot(camToPos, _camera3d.transform.forward)
/ (camToPos.magnitude * _camera3d.transform.forward.magnitude);
var zDistance = camToPos.magnitude * cosine;
The length (magnitude) of camToPos, the vector from the camera to the effect's world coordinates, is the "ordinary distance." Multiply it by the cosine, and you get the Z distance.
Here, camToPos.magnitude appears in both the numerator and the denominator, so it cancels out.
var camToPos = pos - _camera3d.transform.position;
var zDistance = Vector3.Dot(camToPos, _camera3d.transform.forward)
/ _camera3d.transform.forward.magnitude;
Normally you'd simplify the formula in mathematical notation before turning it into code, but writing math notation in a blog is a pain, and more readers are probably comfortable with code anyway, so I wrote it as code first and simplified it afterwards.
Next, you get the scale from the z-direction distance. In this sample, the scale is 1 when the z distance equals uiPlaneDistanceFromCamera. If the distance is twice that, I want the scale to be half, 0.5, so a simple division does it.
var scale = effect.uiPlaneDistanceFromCamera / zDistance;
effect.transform.localScale = new Vector3(scale, scale, scale);
And with that, the calculation is happily complete.
By the way, I suspect Transform.forward always has length 1, but the documentation doesn't say so explicitly, so I divide by it anyway (judging by the example further down the page, it does seem to assume length 1, but...).
Closing
What did you think? Nothing here is especially fancy, but unless you're comfortable with basic vector operations and coordinate transforms, I don't think you'd want to write this kind of code on a daily basis. This showed me that even in the age of Unity, there are tons of things you can't do without understanding vectors.
Incidentally, my recent work hasn't involved vectors at all, so I struggled a bit making this sample. I'd like to do vector-heavy work regularly so my skills don't get rusty.