Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
This post has been wikified, any user with enough reputation can edit it.
avatar image
0
Question by mmelatti · Nov 18, 2014 at 06:09 AM · collisionlinerendererdrawline

Draw a line with collision

Currently I am creating a line using linerenderer This is based on user input via mouse or touch. However, I want to add collision physics to this line. Basically, I want the user to be able to draw a line with their finger and for the player game object to be able to walk on this line.

My idea was to use ray-cast however, I don't know how to implement the code.

Thanks for the help!

Here is my current code: (in C#)

using UnityEngine; using System.Collections; using System.Collections.Generic;

public class DrawLineMouse : MonoBehaviour
{

 public Material newMaterialRef;
 private LineRenderer line;  
 private bool isMousePressed;     
 private List<Vector3> pointsList;     
 private Vector3 mousePos;     
 public GameObject player;
 public int lineNumber; // set in inspector, used to keep track of multiple gameObjects using same C# file
 int counter = 1;        // Keep track of how many times you're touching the screen and building a line.
 // Structure for line points   
 
 struct myLine //I don't think I need this if I'm not using the intersect code. (but whatever)
 { 
     public Vector3 StartPoint;         
     public Vector3 EndPoint;     
 };     
 
 //    -----------------------------------         
 void Awake()     
 {         
     // Create line renderer component and set its property         
     line = gameObject.AddComponent<LineRenderer>();         
     line.material =  new Material(newMaterialRef);  //    Shader.Find("Particles/Additive"   
     line.SetVertexCount(0);         
     line.SetWidth(0.5f,0.5f);         
     line.SetColors(Color.white, Color.white);         
     line.useWorldSpace = true;             
     isMousePressed = false;         
     pointsList = new List<Vector3>();  
 }     
 //    -----------------------------------         
 
 void Update ()      
 {         

     //if (Input.touchCount > 0) {
     //    var touch = Input.GetTouch (0);
             
     if (Input.GetKey (KeyCode.Z)) //delete all lines with button press
     {
         line.SetVertexCount (0);             
         pointsList.RemoveRange (0, pointsList.Count);             
         line.SetColors (Color.white, Color.white);    
     }
     
         if (Input.GetMouseButtonUp (0)) { //every time the user touches screen (mouse) and releases counter goes up (user just create another line)
         counter++;
     }
     if (counter == 11) { //if user makes so many lines, we go back to the original game object, this line (up to 10) will be redrawn.
         counter = 1;
     }

     // If mouse button down, remove old line and set its color to green         
     if (counter == lineNumber) {
         
         if (Input.GetMouseButtonDown (0) ) {             
             isMousePressed = true;             
             line.SetVertexCount (0);             
             pointsList.RemoveRange (0, pointsList.Count);             
             line.SetColors (Color.white, Color.white);    
         } else if (Input.GetMouseButtonUp (0) ) { //touch.phase == TouchPhase.Ended             
             isMousePressed = false; 
         }         
         // Drawing line when mouse is moving(presses)         
         if (isMousePressed) {             
             mousePos = Camera.main.ScreenToWorldPoint (Input.mousePosition); //changed from Input.mousePosition to touch.position        
             mousePos.z = 0;             
             if (!pointsList.Contains (mousePos)) {

                 pointsList.Add (mousePos);                 
                 line.SetVertexCount (pointsList.Count);  
                 line.SetPosition (pointsList.Count - 1, (Vector3)pointsList [pointsList.Count - 1]); 

                 //Instantiate (drawBox, mousePos, rotation.rotation);
                 //Instantiate (drawEdge, mousePos, rotation.rotation);

                 //if (isLineCollide () || isLineCollidedWithOtherObject()) {  //don't end up using this.  
                 //if( OnCollisionEnter() ){

                 if (isLineCollidedWithOtherObject()) {
                     isMousePressed = false;
                     line.SetColors (Color.red, Color.red);                 
                 }             
             } 
             
         } 
         
     }

 } //end update  
 //    -----------------------------------         
 //  Following method checks is currentLine(line drawn by last two points) collided with line      
 //    -----------------------------------         
 
 private bool isLineCollide()     
 {         
     return false; //temp to disable this part of the code
     if (pointsList.Count < 2)            
         return false;        
         int TotalLines = pointsList.Count - 1;        
         myLine[] lines = new myLine[TotalLines];        
         if (TotalLines > 1)          
         {            
             for (int i=0; i<TotalLines; i++)              
             {                
             lines [i].StartPoint = (Vector3)pointsList [i];                 lines [i].EndPoint = (Vector3)pointsList [i + 1];             }        
         }        
         for (int i=0; i<TotalLines-1; i++)          
         {            
             myLine currentLine;            
             currentLine.StartPoint = (Vector3)pointsList [pointsList.Count - 2];            
             currentLine.EndPoint = (Vector3)pointsList [pointsList.Count - 1];            
             if (isLinesIntersect (lines [i], currentLine))                  
             return true;        
         }        
     return false;    
 }
 
 //    -----------------------------------         
 //    Following method checks whether given two points are same or not     
 //    -----------------------------------         
 private bool checkPoints (Vector3 pointA, Vector3 pointB)     
 {         
     return (pointA.x == pointB.x && pointA.y == pointB.y);     
 }     
 //    -----------------------------------         
 //    Following method checks whether given two line intersect or not     
 //    -----------------------------------         
 private bool isLinesIntersect (myLine L1, myLine L2)     
 {         
     if (checkPoints (L1.StartPoint, L2.StartPoint) ||             checkPoints (L1.StartPoint, L2.EndPoint) || checkPoints (L1.EndPoint, L2.StartPoint) || checkPoints (L1.EndPoint, L2.EndPoint))             
         return false;         
     return((Mathf.Max (L1.StartPoint.x, L1.EndPoint.x) >= Mathf.Min (L2.StartPoint.x, L2.EndPoint.x)) &&(Mathf.Max (L2.StartPoint.x, L2.EndPoint.x) >= Mathf.Min (L1.StartPoint.x, L1.EndPoint.x)) && (Mathf.Max (L1.StartPoint.y, L1.EndPoint.y) >= Mathf.Min (L2.StartPoint.y, L2.EndPoint.y)) &&(Mathf.Max (L2.StartPoint.y, L2.EndPoint.y) >= Mathf.Min (L1.StartPoint.y, L1.EndPoint.y)));     
 } 
 

 private bool isLineCollidedWithOtherObject()
 {
     RaycastHit hit;
     Ray ray = Camera.main.ScreenPointToRay(Camera.main.WorldToScreenPoint(pointsList[pointsList.Count-1]));
     if(Physics.Raycast(ray,out hit))
     {
         if(hit.collider)
             return true;
     }

     return false;
 }


}//end public class

/* if (Input.touchCount > 0) { var touch = Input.GetTouch (0); Vector3 touchDeltaPosition = new Vector3 (Input.GetTouch(0).position.x, Input.GetTouch(0).position.y, 0);

 if (Input.GetTouch (0).phase == TouchPhase.Began) {  


     mousePos = Camera.main.ScreenToWorldPoint (touchDeltaPosition);

*/

Comment
Add comment · Show 2
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image robertbu · Nov 18, 2014 at 07:24 AM 0
Share

http://answers.unity3d.com/questions/285040/draw-a-line-in-game.html

avatar image Happyday · Sep 21, 2016 at 02:11 PM 0
Share

Hi, Have you worked out the problem? I have the same idea with you.

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by sysameca · Nov 18, 2014 at 07:26 AM

Logically you would achieve your result by getting the line renderer's mesh or vertices and create a collider from it/them. However it seems that the line renderer's inner code is hidden in the C++ side of Unity so it will be kind of difficult to get any vertices or meshes from it. Basically either you have to roll your own line renderer, which is not that hard or try to find something in the asset store.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

Drawing 2 lines in same time 0 Answers

LineRenderer. Problem with ray displaying 2 Answers

Basic LineRender Reflection 2 Answers

Create a collider for area created by mouse 0 Answers

How to draw a line in unity3d 3 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges