- Home /
2d blocks not attaching using script
What I am trying to achieve is that; the player places blocks of different sizes (I already finished this) but what is broken is the attachment of blocks.
When I run my code, sometimes they attach but not all the time and they glitch around when they do. The code I have reads children with the tag "hatch" and reads other nearby hatches as attachment points and it connects the two parents with a script attached to the hatch. Here is a diagram -
**-
And here is my code-
public class HatchAttatch : MonoBehaviour {
public double maxDistance=.2;
// Use this for initialization
void Start () {
GameObject[] Hatches = GameObject.FindGameObjectsWithTag("Hatch");
//reads hatches worldwide
foreach (Transform child in this.transform){
//reads children
if (child.tag=="Hatch"){
SliderJoint2D[] currentHinge = child.GetComponents<SliderJoint2D>();
for (int a=0;a<Hatches.Length-1;a++)
//goes through worldwide hatches, inefficient, but I will change this later
{
for (int z=0;z<currentHinge.Length;z++){
//goes through child hatches
if (Vector2.Distance(Hatches[a].transform.position,child.transform.position)<maxDistance && Hatches[a].transform.parent!=child.transform.parent&¤tHinge[z].enabled==false)
{
//Probably the cause of the failure
currentHinge[z].anchor=(currentHinge[z].transform.position);
//Probably also the cause of the failure
currentHinge[z].connectedAnchor=(Hatches[a].transform.position);
//connects to the parent's object (I don't connect to other hatch because it won't move its parent)
currentHinge[z].connectedBody = Hatches[a].transform.parent.rigidbody2D;
currentHinge[z].enabled=true;
}
}
}
}
}
}
}
If you need any more info, just ask. Thanks!
hatch diagram.png
(23.3 kB)
Comment
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Rotate HingeJoint2D 0 Answers
Using Tilemap draw tools to change properties with custom editor 0 Answers
Unity 2018 2D Character Jump Glitch 1 Answer