简体   繁体   中英

Unity, 2d, Joints not forming properly through script

When I run a scene, the script checks the four directions from the object, and if there's another object within range, they should form joints with each other. It should do this with every applicable object in the four directions. However, when an object has more than one object within range, it only joints with one of them. It does create the correct number of joints, but only one has it's target game object assigned to it.

The script for each direction is essentially the same, and in my testing it didn't only fail in one direction, so I posted only one directions script here.

Though I do wonder if this has something more to do with general unity behavior?

 [SerializeField]
 private Transform eastPosition;
 [SerializeField]
 private Transform westPosition;
 [SerializeField]
 private Transform northPosition;
 [SerializeField]
 private Transform southPosition;

 float baseCastDistance = 0.2f;


 private void Start()
 {
     CastEast();
     CastNorth();
     CastWest();
     CastSouth();

 }

 void CastEast()
 {
     float castDistance = baseCastDistance;
     Vector3 targetPosition = eastPosition.position;
     targetPosition.x += castDistance;
     Debug.DrawLine(eastPosition.position, targetPosition, Color.cyan, 1000f);

     RaycastHit2D hit = (Physics2D.Linecast(eastPosition.position, targetPosition, 1 << LayerMask.NameToLayer("Blocks")));
     if (hit)
     {
             print("Item in the way: " + hit.rigidbody.gameObject.name);
         gameObject.AddComponent<FixedJoint2D>();
         gameObject.GetComponent<FixedJoint2D>().connectedBody = hit.rigidbody;
     }
 }

Managed to solve it by myself, when creating the joints I store them at the same time, and use that:

void CastEast()
    {
        float castDistance = baseCastDistance;
        Vector3 targetPosition = eastPosition.position;
        targetPosition.x += castDistance;
        Debug.DrawLine(eastPosition.position, targetPosition, Color.cyan, 1000f);

        RaycastHit2D hit = (Physics2D.Linecast(eastPosition.position, targetPosition, 1 << LayerMask.NameToLayer("Blocks")));
        if (hit)
        {
                print("Item in the way: " + hit.rigidbody.gameObject.name);
           Joint2D eastJoint = gameObject.AddComponent<FixedJoint2D>();   
           eastJoint.connectedBody = hit.rigidbody;
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM