Core code
using system;using unityengine;using unityengine.ui;public class testdrawline:monobehaviour{public Image Arrow ; Image material public Recttransform PA; A point public recttransform PB; b Point private void Start () {var RP = Pa.recttransform (). anchoredposition; var tp = pa.position; Debug.Log ($ "a point Transform p: ({tp.x},{tp.y}) Recttransform P:({rp.x},{rp.y})"; }//update is called once per frame void Update () {arrow.transform.position = pa.position; Arrow.transform.localRotation = Quaternion.angleaxis (-getangle (), Vector3.forward); var distance = vector2.distance (pb.anchoredposition, pa.anchoredposition); Arrow.rectTransform.sizeDelta = new Vector2 (Math.max (1, distance-30)); } public float Getangle () {var dir = pb.position-pa.position; var dirV2 = new Vector2 (dir.x, DIR.Y); var angle = Vector2.signedangle (dirV2, Vector2.down); return angle; }}
Related knowledge points
Well, the code is not a few lines but the knowledge points involved are quite many. Feel can be Unity面试题 used to use AH haha.
Gets the angle between two coordinate points
Vector2.SignedAngle(dirV2, Vector2.down)
I've written about this before. For details see the angle value between two vectors in 0~360度 and its practical application
Gets the x, y coordinates of the elements in the canvas
I have a Start difference between the output of the function, the element's Transform.position and (the RectTransform.position actual application should take the anchor point).
The output log is:
Point a Transform P: (98.82188,194.5938) Recttransform P:(-391,130)
Get the distance between two elements in a canvas
This is primarily to note the use of anchoredPosition RectTransform point coordinates in the coordinate system. It Transform is wrong to calculate the distance in the coordinate system.
Direct
Vector2.Distance($A点2D坐标,$B点2D坐标)
Set the width height of the image in Ugui
Using sizeDelta functions
arrow.rectTransform.sizeDelta = new Vector2($宽,$高);
Element rotates around any axis
arrow.transform.localRotation = Quaternion.AngleAxis($旋转角度,$旋转轴)
Uh, four dollar rotation there's nothing to say:(
Unity uses Ugui's image to draw a line in the canvas