Using a cosine wave in Unity for enemy projectile’s movement

Unity
  • Create a script for the ufo prefab’s movement and assign it to the prefab.
  • There are two math values that have a role to play here.
  • Declare these two variables in the script.
float frequency = 1.5f;
int amplitude = 9;
  • Initiate the prefab at a preferred location in the start method.
transform.position = new Vector3(Random.Range(10, -10), 7.0f, 0);
  • In the update method, create another variable that is going to get us the value of transform.position.x.
  • Use Mathf.Cos( ) function and pass an argument of “Time.time * Frequency” in it and, multiply the result with the amplitude.
C#
  • Save this script and create another one for the laser prefab that this ufo shall fire.
  • Declare two variables for the frequency and amplitude of the laser prefab.
private float frequency = 10.0f;  
private float amplitude = 1.5f;
  • In the start method, we need to get the x position on which the prefab gets instantiated. So, declare a variable to hold of x value here.
C#
  • In the update method, everything remains the same as the ufo except for one change without which, the laser prefab will keep getting to the centre of the screen immediately after the instantiation.
C#
  • We are adding the base value we had captured in the start method to the newly create value using the Mathf.cos ( ) function.
  • Lastly, we need to instantiate the projectile from the ufo script so that it starts right where the ufo would be at a given time. So, go back to the ufo script and add a fireLaser( ) method to make this work.
C#
  • The method contains a cooling mechanism to only fire at a regulated interval.
C#

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store