Hello! For a very long time I can not figure out why it works this way.
I have a main GameObject let’s call it parent. I also have child GameObjects, let’s call them child. At first, all objects are the same in hierarchy and have RigidBody2D and BoxCollider2D components, but after I release the mouse button, the child object that I have chosen becomes a child of the parent object, the RigidBody2D component is removed from the child. Now I have a group of objects that behaves like one solid object.
The problem is that although I specify from the code what local position the child should take, its local position is slightly different (and sometimes very different). I have already found out that this is either due to the popping of the collider or due to the Rigidbody. How to solve this problem?
public class Mover : MonoBehaviour
{
private bool isCatchBlock;
private Block catchedBlock;
public GameObject parent;
public Block parentBlock;
public Camera MainCamera;
private Vector2 currentMousePos;
private byte blockCount;
void FixedUpdate()
{
if (Input.GetMouseButtonDown(0))
{
//taking an object
GameObject catchedObj = RaycastHit();
if (catchedObj != null)
{
if (catchedObj.tag == "block")
{
isCatchBlock = true;
catchedBlock = catchedObj.GetComponent<Block>();
catchedBlock.thisCollider.isTrigger = true;
}
}
}
if (Input.GetMouseButtonUp(0))
{
if (isCatchBlock)
{
isCatchBlock = false;
//attaching an object
blockCount++;
//if parent becomes static then everything works correctly BUT "below"
parentBlock.thisRigidbody.bodyType = RigidbodyType2D.Static;
//if child becomes static, then the coordinates are very similar
catchedBlock.thisRigidbody.bodyType = RigidbodyType2D.Static;
Destroy(catchedBlock.thisRigidbody);
catchedBlock.thisTransform.parent = parent.transform;
catchedBlock.thisTransform.eulerAngles = new Vector3();
//everything is always displayed correctly, as it should be
Debug.Log($"Y = {-0.14f*blockCount}");
//but here the real localPosition is not the one I set
catchedBlock.thisTransform.localPosition = new Vector3(0, -0.14f*blockCount, 1);
catchedBlock.thisCollider.isTrigger = false;
//if parent becomes dynamic, then everything works wrong again.
parentBlock.thisRigidbody.bodyType = RigidbodyType2D.Dynamic;
}
}
if (isCatchBlock)
{
//drag child
Vector2 targetPos = (Vector2)MainCamera.ScreenToWorldPoint(Input.mousePosition);
catchedBlock.thisRigidbody.velocity = new Vector2(7 * (targetPos.x - catchedBlock.thisTransform.position.x), 7 * (targetPos.y - catchedBlock.thisTransform.position.y));
}
}
private GameObject RaycastHit()
{
//for convenience
currentMousePos = MainCamera.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(currentMousePos, transform.forward);
return hit ? hit.collider.gameObject : null;
}
}