- Home /
How to create a script for dynamic 2d sprite object that is controlled by 2 vector points?
HI, I need help with a script that is run in the update function that is able to control the length , position and rotation of the line (gameobject) that is controlled by 2 points. Basically I have 3 gameobjects tow represent points in 2d and a third one that acts like a line between the points in 2D. I have the algorithm for position
line.transform.position = (point1 + point2) / 2f;
I need algorithm for rotation and scale. I dont want to mess with the z axis for rotation as it would complicate my scene .
Answer by UnityCoach · Dec 07, 2016 at 12:22 PM
For the scale, if your line object has a nominal length of 1 on X, you can already scale x by the distance between the two points.
For the rotation, you could use LookAt methods, but math is so much more fun :)
Here goes :
using UnityEngine;
using System.Collections;
public class LineTransforms : MonoBehaviour
{
public Transform pointA;
public Transform pointB;
private Vector3 scale;
private Quaternion rotation;
void Start ()
{
scale = transform.localScale;
}
void Update ()
{
scale.x = Vector2.Distance(pointA.position, pointB.position);
transform.localScale = scale;
float angle = Mathf.Atan2(pointB.position.y - pointA.position.y, pointB.position.x - pointA.position.x);
rotation = Quaternion.Euler(0, 0, angle*Mathf.Rad2Deg);
transform.rotation = rotation;
transform.position = (pointA.position + pointB.position)/2f;
}
}