# Move enemy left in sin wave motion over time

I'm trying to create a top down shooting game where the enemy moves in sinusoidal motion over time. For the first 10 seconds the enemy needs to move only left and after that it needs to move left in sin wave motion. This is the code I'm using. 

public float enemySpeed;
float frequency = 5.0f;
float magnitude = 1.8f;

void FixedUpdate()
{
if(Time.time < 10.0f)
{
transform.Translate((enemySpeed* Vector2.left) * Time.deltaTime);
}
if(Time.time >= 10.0f)
{
transform.Translate(enemySpeed* -1.0f * Time.deltaTime, 1.0f * Mathf.Sin(Time.time * frequency) * magnitude * Time.deltaTime, 0);
}


What's happening is that for the first 10 seconds the enemy just moves left but after that all the enemies in the screen start moving in sin wave motion. What I want to achieve is that if the enemy has already spawned before the 10th second, it should move left without sin motion. Right now if the enemy is in the middle of the screen and the time is over 10 seconds, even this enemy starts moving in sin motion.

• Did you mean to use the time since the enemy spawned, instead of the time since the start of the game? – DMGregory Mar 22 at 11:39
• yes.. since the enemy spawned.. – single arrow games Mar 22 at 11:46
• @DMGregory thanks for the help..this is working fine now... – single arrow games Mar 23 at 10:09
• If you've solved your problem, you can click the check mark next to an answer to mark it as "accepted". – DMGregory Mar 23 at 10:29

Just track a variable counting the seconds since this enemy spawned. It can start at zero, and increment each timestep the enemy stays alive.

float secondsSinceSpawn = 0f;

void FixedUpdate() {
secondsSinceSpawn += Time.deltaTime;

if(secondsSinceSpawn < 10f) {
...


You can save the enemy spawn time in Start, then compare that to the current time like this:

float enemySpawnTime;

void Start()
{
enemySpawnTime = Time.fixedTime;
}

void FixedUpdate()
{
if (Time.fixedTime - enemySpawnTime < 10f)
{
// move left
}
else
{
// move left with sine wave motion
}
}


Note that in FixedUpdate, you should use Time.fixedTime or Time.fixedDeltaTime instead of Time.time.

• In FixedUpdate, Time.deltaTime returns Time.fixedDeltaTime automatically, so you don't have to manually change it. The same goes for Time.time, which returns fixedTime automatically when accessed in FixedUpdate. This makes it easier if you're refactoring code from update to fixed or vice versa — the appropriate time step will be substituted automatically. – DMGregory Mar 22 at 14:09
• @Sirius 5 , thanks for the help.. I was able to implement what DMGregory advised and its working now. – single arrow games Mar 23 at 10:10