I am working on a study/test app in which one of the question types is matching. I am using unity ui and am looking of an idea or way to draw lines from the users selected word to the answer they selected. I have the user selection along with the answer checking all coded and working great but cannot figure out the visual effect portion for drawing a line from word to answer.
Any help or ideas would be great. Thanks in advance.
Well after a little trying here is what I have come up with if anyone else is looking for something like this.
Call select word when you click the word or question and it runs selecting answer until an answer is selected, which in turn causes the line to follow the cursor. This is only the portion of the code dealing with the line creation/scaling. The linePrefab is just an Image element saved as a prefab. After the answer is clicked the line is moved to the center of the question box at the right side and the center of the answer box on the left side.
//Extraneous details omitted
IEnumerator SelectingAnswer()
{
line = Instantiate(linePrefab) as Image;
line.rectTransform.SetParent(rt, false);
line.rectTransform.sizeDelta = new Vector2(0, 5);
startClick = Input.mousePosition;
line.rectTransform.anchoredPosition = startClick;
while (selecting) {
line.rectTransform.sizeDelta = new Vector2(Vector2.Distance(startClick, Input.mousePosition)-5, 5);
float rot = 0;
if(Input.mousePosition.y > startClick.y){
rot = Vector2.Angle(Vector2.right, new Vector2(Input.mousePosition.x, Input.mousePosition.y) - startClick);
}else{
rot = -Vector2.Angle(Vector2.right, new Vector2(Input.mousePosition.x, Input.mousePosition.y) - startClick);
}
line.rectTransform.eulerAngles = new Vector3(0,0,rot);
yield return 0;
}
}
public void SelectWord(RectTransform clicked)
{
if(selecting)
return;
tempWord = clicked.GetComponent<Text>().text;
wordRight = new Vector2(clicked.position.x + clicked.rect.width/2,clicked.position.y);
selecting = true;
StartCoroutine(SelectingAnswer ());
}
public void SelectAnswer(RectTransform clicked)
{
if (!selecting)
return;
selecting = false;
float rot;
line.rectTransform.anchoredPosition = wordRight;
answerObj = clicked;
tempAnswer = answerObj.GetComponent<Text>().text;
answerLeft = new Vector2(answerObj.position.x - answerObj.rect.width/2,answerObj.position.y);
if(answerLeft.y > startClick.y){
rot = Vector2.Angle(Vector2.right, answerLeft - wordRight);
}else{
rot = -Vector2.Angle(Vector2.right, answerLeft - wordRight);
}
line.rectTransform.eulerAngles = new Vector3(0,0,rot);
line.rectTransform.sizeDelta = new Vector2(Vector2.Distance(wordRight, answerLeft), 2);
//CheckAdd (); Used to check answers
}
3 Likes