Moving Object Left/Right Accounting for Rotation

Hey Y’all,

I am trying to create projectiles in my game that move laterally in a sine wave while also continuing forward. I have this code from another project that moves objects in a sine wave along x coordinates.

void Start()
    {
        x0 = transform.position.x; //gets the x value of pos (a property defined in the Enemy class)
        birthTime = Time.time; //gets the time the object was created
    }
 Vector3 tempPos = transform.position;
        //theta adjusts based on time
        float age = Time.time - birthTime; //gets difference between the current time and when Start() was called
        float theta = Mathf.PI * 2 * age / waveFrequency; //gets (Pi * 2) * (age / waveFrequency)
        float sin = Mathf.Sin(theta); //gets the Sine of theta (above)
        tempPos.x = x0 + waveWidth * sin; //creates the new x position based on where it started, the width of the sine wave, and the sine value
        transform.position = tempPos; //moves the object to the new position

I also have this code to move the object forward:

        Vector2 newPos = transform.position;
        newPos = transform.position + (transform.up * moveSpeed * Time.deltaTime);
        transform.position = newPos;

What I want is to take the top code and make it make the object move left and right according to its rotation, not just along x and y coordinates, and then still move it forward as it would have to begin with. I feel like there’s a simple trick I’m missing that could convert the x movement to something that conforms to rotation, but I haven’t been able to crack it myself. Can anyone help?

Yeah, I meant “up” not forward. Thanks, I’ll give this a try.

Hi,

If you want to move the object left/right, regarding of its rotation, you can use transform.right or transform.left vectors.
To create your sinusoidal left/right movements, you can do :

transform.position += transform.right * waveWidth * sin;

Be careful, because you said :

But you’re moving your object towards the up vector of your transform. (so transform left/right might not be what you want in your situation)

If you need to use time since startup, Unity has something like this called Time.realtimeSinceStartup : https://docs.unity3d.com/ScriptReference/Time-realtimeSinceStartup.html

Hope this will help you !