- Home /
object movement as wave in Unity 3d
I created a object in unity
GameObject monsterclone = (GameObject)Instantiate(monsterPrefab, floorPosition, Quaternion.identity);
This object should move in a wave style from a specific point to another.
Vector3 nPos = mfloorPos + new Vector3(2f, 0f, 0f);
Vector3 oPos = mfloorPos + new Vector3(-2f, 0f, 0f);
How can I do it?
Answer by tmdchi · Apr 05, 2013 at 11:01 AM
Try using the Mathf.Sin() function using Time.time as the parameter, and tweak according amplitude, phase, etc.
Answer by sia · Apr 05, 2013 at 01:22 PM
Here's a WaveLerp function. It works like Lerp(), but with a sinusoidal displacement along the path in the plane given by the 'up' vector, and with given amplitude and frequency.
Call the Coroutine with: StartCoroutine(WaveMove(monsterclone.transform, nPos, oPos, 1f));
IEnumerator WaveMove(Transform obj, Vector3 origin, Vector3 dest, float speed)
{
float distance = (dest - origin).magnitude;
float totalTimeToMove = distance/speed;
float timeElapsed = -Time.deltaTime;
float fraction = 0f;
while(fraction < 1f) {
timeElapsed += Time.deltaTime;
fraction = timeElapsed/totalTimeToMove;
obj.position = WaveLerp(origin, dest, Vector3.up, 0.5f, 1f, fraction);
yield return null;
}
}
Vector3 WaveLerp(Vector3 origin, Vector3 dest, Vector3 up, float amplitude, float freq, float fraction) {
float x = fraction * (dest - origin).magnitude;
float w = 2*Mathf.PI * freq;
float y = amplitude * Mathf.Sin(w*x);
Vector3 xDir = (dest - origin).normalized;
Vector3 yDir = Vector3.Cross(xDir, up).normalized;
Vector3 pathOffset = x * xDir;
Vector3 waveOffset = y * yDir;
return origin + pathOffset + waveOffset;
}
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Character Rotation 2 Answers
Smooth Camera/Object Movement 1 Answer
Smooth rotation... 1 Answer
Alternative of touchesMoved in Unity3D 0 Answers