I just wrote a script for snapping two object together, firstly function should find the direction of obj[1](object that should stick to parent object), I want the function (detect) returns only one result (single direction), but sometimes returns two direction for example : at the same time returns : left and down here is my question what is the main problem of my script how can I fix it ? most of the time can’t detect top btw
Thank you.
public Transform [] obj = new Transform[2];
public bool run = false;
float distance = 5.0f;
public Pipe_in p_in;
public int direction = -1;
public void Detect_Direction ()
{
if (p_in.loop_move_cycle_of_Pipes_in == false)
{
obj [0] = GameObject.Find (p_in.Switch_B.name).GetComponent<return_pipe_name> ().Pipe;
obj [1] = p_in.Switch_B;
Vector3 offset = obj [0].position - obj [1].position;
offset = offset.normalized;
Vector3 up = obj [1].InverseTransformDirection (Vector3.up).normalized;
Vector3 down = obj [1].InverseTransformDirection (Vector3.down).normalized;
Vector3 left = obj [1].InverseTransformDirection (Vector3.left).normalized;
Vector3 right = obj [1].InverseTransformDirection (Vector3.right).normalized;
Debug.Log ( "Up: " + Vector3.Dot(up, offset).ToString() +
" Down: " + Vector3.Dot(down, offset).ToString() +
" Right: " + Vector3.Dot(offset, right).ToString() +
" Left: " + Vector3.Dot(left, offset).ToString());
if (Vector3.Dot (up, offset) > 1) // before: > 0
{
print ("obj[1] : Up");
direction = 0;
}
if (Vector3.Dot (down, offset) < Vector3.Dot (left, offset)) // before: < 0
{
print ("obj[1] : Down ");
direction = 1;
}
if (Vector3.Dot (right, offset) > 1) // before: > 0
{
print ("obj[1] : Right");
direction = 2;
}
if (Vector3.Dot (left, offset) < Vector3.Dot (down, offset)) // before: < 0
{
print ("obj[1] : left");
direction = 3;
}
float mag = offset.sqrMagnitude;
if (mag < distance * distance)
{
obj [1].transform.position.Normalize ();
obj [1].transform.parent = obj [0].transform;
if(direction == 0)
obj [1].transform.localPosition = Vector3.up;
if(direction == 1)
obj [1].transform.localPosition = Vector3.down;
if(direction == 2)
obj [1].transform.localPosition = Vector3.right;
if(direction == 3)
obj [1].transform.localPosition = Vector3.left;
}
if (direction != -1)
p_in.Switch_B = GameObject.Find ("x").transform;
}
}
