- Home /
How to rotate a line by its other end at runtime?
So basically i want to rotate a line by its other end. More clearly, i draw one straight line which is 10x1 long. I want to grab one of its end with the mouse and than it would rotate around its other ends positions. Is this possible?
Answer by unity_ek98vnTRplGj8Q · Dec 19, 2019 at 10:35 PM
Here is a short script I made that accomplishes what I think you are asking for. Keep track of the ends of the line with two points and just use Camera.ScreenToWorldPoint(Input.mousePosition)
to rotate the points. If this doesn't do what you want it should at least give you an idea of what you need to do.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DisRotTest : MonoBehaviour
{
public Transform point1, point2;
public Camera cam;
private LineRenderer lr;
private Transform grabbedPoint, stationaryPoint;
private Vector3[] lrPoints;
void Start()
{
//Set the initial line length to 10
point2.position = point1.position + 10 * Vector3.up;
//I'm using a line renderer to draw the line
lr = GetComponent<LineRenderer>();
lrPoints = new Vector3[2];
//Tell the line renderer to update its points
SetLinePoints();
grabbedPoint = stationaryPoint = null;
}
private void Update()
{
//Grab mouse position every frame
Vector3 mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
//I want to rotate on the X-Y plane, so I'm going to align the mousePosition with my gameObject on the Z axis
mousePos.z = transform.position.z;
//When we click, grab the closest point
if (Input.GetMouseButtonDown(0))
{
grabbedPoint = Vector3.Distance(mousePos, point1.position) < Vector3.Distance(mousePos, point2.position) ? point1 : point2;
stationaryPoint = grabbedPoint == point1 ? point2 : point1;
}
//While we drag, make the line go through our mouse position
if (Input.GetMouseButton(0))
{
Vector3 offset = mousePos - stationaryPoint.position;
offset = offset.normalized * 10; //Set line length to 10
grabbedPoint.position = stationaryPoint.position + offset;
}
//Tell the line renderer to update
SetLinePoints();
}
private void SetLinePoints()
{
lrPoints[0] = point1.position;
lrPoints[1] = point2.position;
lr.SetPositions(lrPoints);
}
}
Your answer
Follow this Question
Related Questions
Line Renderer Rotation Issue 2 Answers
Line renderer rotation and alignment 1 Answer
About Tile Texture for 2D Line Renderer 0 Answers
slowly rotate a object *need quick fix* 0 Answers