Move a RigidBody with MovePosition up and down

Hello,

I need to Move slowly a RigidBody with MovePosition up and down.


This object that I need to move is child of another object just to let you know it.
I am close but it doesn’t work. It’s 3 days I stucked on this, please help!!

I tried something like this but doesn’t work.

void FixedUpdate() {
         
       float newY = Mathf.Sin(Time.time);
       Vector3 direction =  ((new Vector3(0, Mathf.Abs(newY)* height,1)) -transform.localPosition).normalized;
           r.MovePosition(transform.position + direction * movementSpeed * Time.deltaTime);
        
    }

Could you write a working code for make this work please?

Why do you normalize the direction vector?

Try the following code, but I don’t know if it will fit your needs:

private Vector3 initialPosition;
private Rigidbody r;

void Start()
{
    r = GetComponent<Rigidbody>();
    initialPosition = r.position;
}

void FixedUpdate()
{          
    float newY = Mathf.Sin( Time.time * movementSpeed ) * height;
    Vector3 position = new Vector3( 0, newY, 1 ) - initialPosition ;
    r.MovePosition( position );
}