How to place turret on the Terrain

Suleiman Abdullah
3 min readMar 16, 2024

--

Object: How to place turret on the Terrain.

Before doing anything I just prepare simple terrain using primitive circle and I have create primitive turret, then I remove all collider in the turret.

In the first step create a transform variable called turret ,then check if we hit something using physics dot RayCast, if we hit something we place a turret at hit point.

Note: I assume you have knowledge about Interaction Logic ,if not go check my article about Interaction I have cover basic of interaction.

How we will place the turret ?

Lets see what we have, we have a ray direction ,surface normal and hitPoint.

Now we need to do a cross product between normal and ray direction ,this will provide us x axis.

If you pass ray direction first you will have x axis point in wrong direction.

To Visualize it I will use gizmos to drawRay of x-axis and normal.

There is the a formula in the cross product ,if you do a cross product of X and Y equal z axis. Now we have y axis which is normal of the surface and x axis.

I draw a Gizmos to visualize the Z axis.
a blue ray is Z axis.

To apply these axis's to our turret we do this using Quaternion.LookRotation.This method take forward vector and up vector which will be z axis and hit.normal.

But wait ,if we do like this our turret wont face forward in correct way especialy if our camera face down ward.

To solve this we need to use camera x local basis vector us x axis in the dot product .So our by doing this first we need to get rid of the axis .

This is how to place a turret on terrain

If you find issue when place a turret on the wall if your game need to do that use first solution on the wall and the second on terrain.

See you in the next one.

--

--

Suleiman Abdullah

Self taught Unity Developer, who is passion about making games ,and he loves Math For Game Development