transform.position Mathf.Sin

Hi, how do I write in code to make an object moves up and down in an axis like a sine wave? Thank you very much.

http://upload.wikimedia.org/wikipedia/commons/7/77/Waveforms.svg

1 Like

Hi

There’s a script in the 3D Platform Tutorial to handle this, search for the LaserTrap in the document.

See ya

Thanks. I’m getting the object to move up and down now. But, how do I make it move in x-axis. I can’t get it move in Time.deltaTime.

var height = 3.2;
var speed = 2.0;
var timingOffset = 0.0;
var count=0;

function Update()
{
count++;
	var offset = Mathf.Sin(Time.time * speed + timingOffset) * height / 2;
	transform.position = Vector3(count, offset, 0);

}

The code you are using moves the object in the X axis by one unit each frame. To make it move at one unit per second, use something like this:-

   ...
var count=0.0;

function Update()
{
   count += Time.deltaTime;
	var offset = Mathf.Sin(Time.time * speed + timingOffset) * height / 2;
	transform.position = Vector3(count, offset, 0);

}
2 Likes

wow thanks. That’s what I’m looking for.

Aaaand some years after, it’s also what i was looking for.

And even from farther ahead in the future, this is what I am looking for.

Every two years someone comes across this post and is helped. Thank you for the great question, and the great answer!

I think this has just solved my problem too! Thanks!

A bit over 9 years later it also solved my issue, cheers!

woooo I time travelled to 2019 and got helped by this. thanks