- Home /
Attaching game objects with joints - Matching angles
I'm working on a 2D space combat game, and the feature I'm having a problem with is in attaching two spaceship objects together to dock them.
I'm using a slider joint to attach the ships together and move the smaller ship around the hangar of the larger one. The problem is in setting the angle property of the slider joint. When the carrier is facing north or south, everything works, but when facing any other direction, the small ship jumps from one point to another since the angle is not set correctly. Here's a gif of the results I get, and below is the relevant code. How do I set the angle properly?
private GameObject HangarShip, CarrierShip;
private Vector3[] IntermediatePoints;
internal void Move(int desiredPosition, SliderJoint2D joint)
{
CurrentPosition = Math.Max(-1, Math.Min(desiredPosition, IntermediatePoints.Length));
//sets next point for the docked ship to slide to
if (CurrentPosition == -1)
{ joint.connectedAnchor = RestingPostion; }
else if (CurrentPosition == IntermediatePoints.Length)
{ joint.connectedAnchor = Runway; }
else { joint.connectedAnchor = IntermediatePoints[CurrentPosition]; }
//this line does not work properly
joint.angle = (GetAngle(HangarShip.transform.position, CarrierShip.transform.TransformPoint(joint.connectedAnchor.x, joint.connectedAnchor.y, 0f)) - 90);
}
float GetAngle(Vector3 start, Vector3 target)
{
if (target.y == start.y)
{ return (start.x > target.x) ? 180 : 0; }
if (target.x == start.x)
{ return (target.y > start.y) ? 90 : 270; }
float tangent = (target.x - start.x) / (target.y - start.y);
double ang = (float)Mathf.Atan(tangent) * 57.2958;
if (target.y - start.y < 0) ang -= 180;
return (float)ang;
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613175947im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Child versus Parent rotations 3 Answers
Affine transformations to Object 3 Answers
Changing the forward rotation for LookAt 2 Answers
How to change the length of the object with configurable joint attached 0 Answers
Make 3D Player look exactly at mouse with ScreenToWorldPoint? (maths Question) 2 Answers