Operate a cannon using UI buttons in Unity
Objective: Create a system to use UI Buttons to control a cannon.
We can use buttons to control objects in a game. We need to set up the cannon before we get into the buttons. I downloaded this turret from Filebase.
Next we will create a cannon script, this script will control how the cannon will act. In this script we will need a reference for the turret barrel, a cannonball, and a spawn point for the cannon ball. We will also need a vector3 and a quaternion for the cannon as a whole and the turret.
We will start with just rotating the cannon around the Y axis. To do this we will create a public method named Rotate. It’s public for later use with buttons. We will allow for a pass in variable type int.
In this method we will assign our _currentBaseAngle to a new vector3 while passing in the rotate variable to the Y axis. Next we will assign the _currentBaseQuaternion.eulerAngles to equal the baseAngles. Finally assign the game objects rotation to the quaternion.
For raising and lowering the turret, we will follow a similar path as rotate but instead of passing it in to the Y axis, we will do the Z axis. When we are finish we will assign the local rotation of the turret to the quaternion. I put a limit on the angle. I checked to see if the angle is less than -60 and assign to -60 to lower it down to 0. I returned after this so it doesn’t pass this limit.
To check and make sure this worked we can check for player input in Update and calling the correct method and passing in the angles.
Finally we will set up the last method in the Cannon script, Fire(). We will make this public as well. In here we will assign GameObject Projectile to the Instantiated object. For Instantiate we will pass in the _cannonBall, Spawnpoint’s position, and the turrets rotation. Next we will get the Rigidbody of the Projectile and add relative force to it.
Before we assign the cannonball in the inspector, we need to create a prefab.
Once the Prefab is made, we can drop it into the turret script.
Now the cannon is done, time to set up the buttons. I created 5 buttons, one for each direction and one for firing.
In each button I added an event. I than dropped in the turret game object to grab the cannon script. I selected the Rotate for left and right buttons and passed in 15 and -15 respectfully. I than selected the RaiseOrLower method on the up and down buttons and passed in 15 again. I did the same for the last button but selected the Fire Method.
With that our buttons control our cannon now. Thanks for reading and have a wonderful day!