a guest Feb 18th, 2020 85 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
- Good Afternoon Group Shinies,
- Raycasting is commonly done but fairly complex. The unity component used to visually draw a line of light is called a "Line Renderer" I had hoped that there was an easy way to detect collisions using this renderer. However, it seems that this component does not support true raycasting. Although, it can be made to detect collisions, the solutions are more like workarounds and are fairly complex:
- See below for what I mean:
- I suggest that "true" raycasting be performed in code and the line renderer updated from code as needed based on the rays generated from code. This may sound painful, but is not too bad in practice. I recommend looking here:
- Here is an example:
- void Update()
- // Bit shift the index of the layer (8) to get a bit mask
- int layerMask = 1 << 8;
- // This would cast rays only against colliders in layer 8.
- // But instead we want to collide against everything except layer 8. The ~ operator does this, it inverts a bitmask.
- layerMask = ~layerMask;
- RaycastHit hit;
- // Does the ray intersect any objects excluding the player layer
- if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, Mathf.Infinity, layerMask))
- Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * hit.distance, Color.yellow);
- Debug.Log("Did Hit");
- Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * 1000, Color.white);
- Debug.Log("Did not Hit");
- Of note here is the following: Physics.Raycast will send out a ray from the chosen origin point to the chosen destination point. It will return true if it hits something and whatever it hits will become the variable "hit". The ray will be invisible.
- To see the ray quickly, without much style, you can use Debug.DrawRay like this example to actually draw a colored line.
- I recommend adjusting the Line Renderer in code based on collisions from the above example. Please let me know on Thursday if you have any questions about the example.
RAW Paste Data