How much an object is facing another object.

I’m fairly new to game dev so I apologize if this is actually an easy fix. I’m making a game that has solar panels. I want the solar panels to generate at 100% efficiency when facing the sun head-on. but generate less and less power as the panels turn away from the sun. the solar panels are on a moving vehicle and the sun is moving on a day/night cycle if that’s important information to know. I’m just hoping if someone can point me in the right direction of how to make this work.

There’s a “normal” vector for the surface of your panel. This is a vector pointing in the direction of the surface of the panel. What that vector is, is up to you. Lets say your ‘mesh’ is drawn to have the “Y” axis of its GameObject be that direction, you can just use that (or some other axis), that’s the easiest way to do it. If it’s not setup that way, well you should probably resetup your mesh to use some known axis. Otherwise you’re going to have to find a poly on the surface of the mesh and calculate it from that.

Point is… get the normal vector of your panel.

Next get the vector that is most optimal to point at the sun. If you consider most optimal is pointing at a specific point in the sky… just subtract the panels position from that point, normalize it, and that’s your vector. If it’s just a “direction” like how the “Directional Light” works… then use that vector (if you do this you may need to * -1 the vector to make sure you account for the opposite direction of the sun towards panel vs panel towards sun).

Now with this information you can do a few things…

Vector3.Angle:

This gives the angle between both vectors, 0 means they’re facing the same direction. Note if you used the ‘direction light’ the vector of your lightsource may be backwards and return 180 degrees when parallel just due to the nature of your setup.

Vector3.Dot:

If you normalize your vectors, then you take the dot product, a value of 1 means they’re parallel and the values get closer to 0 as they become adjacent, and towards -1 as they go opposite and parallel again. Technically speaking Angle just uses the ‘Dot’ and acos the result to get the angle.

From this it is up to you to decide how to scale to your “power generation” levels you want. What does 45deg off mean? What does 90deg off mean? So on.

Adding to what @lordofduct said above (which is 100% awesomeness), if you have a solar array model that is already angled at some degrees, you can put it into a prefab along with an extra empty GameObject that can inform you of the normal, by being locally rotated so the +Z faces the normal. You would in the editor align that to whatever you want to consider the solar array’s normal, then do all the stuff Lord said above.