How to get the "Perfect" Sine Wave Pattern

Hello folks,

I already managed to move a gameobject in a sine wave pattern thanks to this answer: How to make projectile to shoot in a sine wave pattern - Questions & Answers - Unity Discussions

In my 2D game the level designer is able to place enemies by inputting on the Inspector their start_pos and their end_pos. The enemy will then calculate the direction and move towards.
My problem is: I can’t figure out how to automatically get the axis in which the sin wave will move depending on the direction.

Example: if my direction is (1.0, 0.0), the axis must be (0.0, 1.0), but if the direction is (0.0, 1.0), the axis must be (1.0, 0.0). And I can’t figure out how to make this calculation automatic. So my level designer doesn’t need to care about it. Do you have any possible suggestion other than manually input the axis in the Inspector?

Thanks in advance.

Sounds like you need to learn about vector maths?

You can work out a directional vector by doing:

Initial Position - Target Position.

You can also then get the square magnitude of that vector to find its length, or “distance”. (not useful here but useful for other things).

So try:

Vector3 direction = transform.position - target.position;

then normalize this to turn it into a direction (unit vector)

direction.Normalize();

you can then use this to work out what direction they are initially facing as they start moving etc.

Then you can flip this direction by multiplying it negatively like this : direction = -direction;
So once you work out the direction, you can then use it to affect your wave, simple!

Vector3 direction = … ;
Vector3 axis = Vector3.Cross( direction, Vector3.up )

Or maybe try this, depending on your needs :

Vector3 direction = ... ;
Vector3 axis = Vector3.Cross( direction.x < 0 ? -direction : direction, Vector3.up )