Movement Relative to Rotated Parent


I’m trying to create a child-object (rigidbody2D) inside another rigidbody2D. I can move them seperately which works fine. The parent object is rotating when pressing left and right, the child object is moving directly over the X and Y axis (so left and right, no rotation involved).

The big problem is that when parent objects are rotated, the child objects are still moving in straight lines X and Y. So relative to the parent they are moving in wrong directions.

public void moveRight()
        rigidbody2D.velocity =  new Vector2(1, 0);
    public void moveLeft()
        rigidbody2D.velocity = new Vector2(-1, 0);
    public void moveUp()
        rigidbody2D.velocity = new Vector2(0, 1);
    public void moveDown()
        rigidbody2D.velocity = new Vector2(0, -1);
    public void moveStop()
        rigidbody2D.velocity = new Vector2(0, 0);

The problem is that the velocity is set not taking into account the parent object.

rotationInDegrees = Mathf.Atan2(attachedTo.rigidbody2D.position.y,
attachedTo.rigidbody2D.position.x) * Mathf.Rad2Deg;

I can use this with Cos and Sin. But I never can get it quite right.

Instead of directly setting the velocity I found/came up with the following code, but again it is not taking into account the parent’s rotation.

void FixedUpdate(){
    attachedTo.rigidbody2D.position.x) * Mathf.Rad2Deg;
    rigidbody2D.velocity = new Vector2(Mathf.Lerp(0, Input.GetAxis("Horizontal") * 5, 0.8f),
                                    Mathf.Lerp(0, Input.GetAxis("Vertical") * 5, 0.8f)); 

I’m currently lost as I want the character to move by the last piece of code but also take into consideration the parent’s angle to move in the right direction…
Any piece of advice on how to do this? Or possibly an answer?! Ive been looking but haven’t found an answer on the interwebs…
Sidequestion: can I force the rigidbody2D to stay inside the parent?

Physics is not performed relative to the parent - it all happens externally, then the world-space values for rigid body positions get put back into the objects.

One option you have is to use constraints to constrain the child to the parent’s axis. This will give a physically plausible result when the parent rotates while the child is already moving. Look them up if it sounds useful.

You might also want to apply your forces relative to the parent, so instead of using Vector2(1, 0) you can transform it using the parent’s transform, to get a new world-space vector that’s not just along the world X axis.

Vector2 worldVector = parent.transform.TransformVector(localVector);

It really depends what you’re trying to do, and actually I find myself doubting that you really want physics involved here at all. You may be better off just not using rigidbody2d at all.