Greetings,
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?