Hey, my question is how do i instantaite the object, so that the spawn would always be perpendicular to another object, and rotation as well. I want the Y axis to alwyas be perpendicular to the line, even if the line has rotated. Its simply a Ray, drawn from one gameObject, to another.
Have you tried setting transform.right to the direction of the line? This should align the red arrow with the line.
Otherwise regular trigonometry should let you calculate the z angle your sprite needs to have its up axis align with the red line.
using UnityEngine;
using System.Collections;
public class Align : MonoBehaviour {
// Move the from and to transforms in the editor at runtime and watch the align transform align and place itself in between.
public Transform from;
public Transform to;
public Transform aligned;
void Start () {
if (from == null)
from = new GameObject ("from").transform;
if (to == null)
to = new GameObject ("to").transform;
if (aligned == null)
aligned = new GameObject ("aligned").transform;
}
void Update () {
Vector2 offset = to.transform.position-from.transform.position; // Get an offset vector, get the opposite and adjacent of a right triangle
float radian = 0f;
if (offset.x != 0f) {
radian = Mathf.Atan (offset.y / offset.x); // Arc tangent of opposite/adjacent to find angle
if (offset.x < 0f) {
radian += Mathf.PI; // enable 360 degrees, disable if you want green line above red at all times
}
}
aligned.eulerAngles = new Vector3 (0f, 0f, radian * Mathf.Rad2Deg); // Set the angle.
// Debug stuff:
aligned.transform.position = (from.transform.position + to.transform.position) * 0.5f;
Debug.DrawLine (from.transform.position, to.transform.position, Color.red);
Debug.DrawLine (aligned.transform.position, aligned.transform.position + aligned.transform.up, Color.green);
}
}