简体   繁体   English

在 Unity3d 中使用 Raycast 使 LineRenderer 可点击

[英]Making LineRenderer Clickable with Raycast in Unity3d

I'm currently working on a project where I'm generating trees/plants with a line renderer and the l-system.我目前正在从事一个项目,我正在使用线渲染器和 l 系统生成树木/植物。 Now I want to be able to click on the different plants to update their fitness score.现在我希望能够点击不同的植物来更新它们的健康分数。

I tried to bake a mesh and use a mesh collider but it didn't work.我尝试烘烤网格并使用网格对撞机,但没有成功。

What would be the best way to approach this?解决这个问题的最佳方法是什么? Thank you in advance.先感谢您。

This is the part where I'm using the LineRenderer to generate the plants:这是我使用 LineRenderer 生成植物的部分:

 public PlantDNA Generate(Bounds bounds) { Tree = Instantiate(treeParent); currentString = axiom; StringBuilder sb = new StringBuilder(); //L-System for (int i = 0; i < iterations; i++) { foreach (var c in currentString) { // adds value onto string builder sb.Append(rules.ContainsKey(c)? rules[c]: c.ToString()); } currentString = sb.ToString(); sb = new StringBuilder(); //Debug.Log(currentString); } for (int i = 0; i < currentString.Length; i++) { switch (currentString[i]) { case 'F': Vector3 initialPosition = transform.position; transform.Translate(Vector3.up * 2 * length); GameObject treeSegment = currentString[(i + 1) % currentString.Length] == 'X' || currentString[(i + 3) % currentString.Length] == 'F' && currentString[(i + 4) % currentString.Length] == 'X'? Instantiate(leaf): Instantiate(branch); treeSegment.transform.SetParent(Tree.transform); treeSegment.GetComponent<LineRenderer>().SetPosition(0, initialPosition); treeSegment.GetComponent<LineRenderer>().SetPosition(1, transform.position); treeSegment.GetComponent<LineRenderer>().startWidth = width; treeSegment.GetComponent<LineRenderer>().endWidth = width; break; // axiom case 'X': break; default: throw new InvalidOperationException("Invalid L-Tree Operation"); } } PlantDNA plant = Tree.AddComponent<PlantDNA>(); AssignFirstPlantRule(plant); return plant; }

This is the fitness function with raycast:这是带有光线投射的健身 function:

 public void FitnessFunction() { for (int i = 0; i < population.Count; i++) { if (Input.GetMouseButtonDown(0)) { RaycastHit hit; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray, out hit, 100.0f)) { if (hit.transform.gameObject == population[i].gameObject) { // Fitness Score um 1 erhöhen population[i].fitnessScore += 1; Debug.Log(population[i].fitnessScore); } } } } }

plants植物

First, you need cahsed treeSegment.GetComponent<LineRenderer>() - its loaded method.首先,您需要 cahsed treeSegment.GetComponent<LineRenderer>() - 它的加载方法。 Just For raycast you needed Collision component and RigitBody component on clickable object .仅对于光线投射,您需要在可点击的 object 上使用Collision 组件RigitBody 组件 I see, you additing mesh collider.我明白了,你添加了网格对撞机。 But are you addition RigitBody?但是你添加了 RigitBody 吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM