Tuesday, December 3, 2024

Tutorial: Controlling a Tank Turret


 

    I like the phrase "Using a sledgehammer to crack walnuts" and this tutorial might just be that, but I'm going to take you through how I got the tank barrel to track the player in Nuclear Lizard Island Rampage, and maybe you can pull a better way out of this. The tank turret is actually made up of three separate independent pieces; the turret (round bit) the barrel (long bit) and the sight (invisible bit). The sight is the simplest and most important part. So, we'll go over that first. 

 


    The sight works off an incredibly simple billboard script. It's only job is to know where the players head is (Get Variable - Player_Head) and face it (Look At - Target) and it does it on an Update schedule, meaning every single frame. This script is slapped on an invisible object with no collider attached to the top of the tank. It's just there to act as a compass for the other bits.

    Side note, the "players head" is an empty object stashed inside the players capsule collider roughly where the head might be. I originally had this script just pointing at the player, but when I did that, everything pointed at the players feet since that was their origin/pivot point and it looked a bit weird.


    

     The tank turret (round bit) is also updating every frame. The first block it hits is an If block hooked up to a large, spherical trigger attached to the tank. If the enemy player is in the trigger area, a boolean gets flipped on and the If block reads as True, moving onto the block where we create a rotation. 

    Pulling from the Sight, which is hooked up as an object specific variable, we get the rotation and from that we pull out just the Y and W rotations. The X and Z have to stay at 0 so the turret only spins around on one axis. Then we move onto the Set Rotation block and feed in our very stripped down rotation data to the Turret, which is also an object specific variable. So, now we have the turret facing in the general direction of the player, but only when the player is in range, and we stopped it from looking up or down.



    The barrel (long bit) works in the exact same way as the tank turret, but we don't strip out any of the rotation data. So, the barrel is free to look the player directly in the eye (or camera) as long as they're in range. The whole effect only works because the turret and barrel are on the same update schedule and were modeled with the exact same pivot point, but it does work, and this whole mess of objects and scripts smoothly rotates to face the player whenever they get into firing distance.

     Thanks for reading. If you want more maybe buy the game this script came from or just throw me something on Ko-Fi and I can justify making some more Visual Script write ups. I have a lot of other half-baked scripts to share.


 

No comments:

Post a Comment