I need help to make a Ray hit a 2D sprite hexagon map.
I also need to be able to select and detect 3D models aswell as the sprites, is it possible for me to do both?
Thanks guys.
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo))
{
RaycastHit2D hit = Physics2D.GetRayIntersection(ray, Mathf.Infinity);
if (hit.collider != null)
{
Debug.Log("Uncle Ray Ray hit someone ");
}
}
}
}
Answer by Zorbaxy · Apr 05, 2017 at 08:40 AM
Try with Physics.RaycastAll function. Both 2D (Sprites) and 3D objects should have 3D colliders on them. Put a 3D collider on an empty child game object and resize the collider to size appropriate to your sprite. Physics2D.RaycastAll will hit only 2D colliders, and Physics.RaycastAll only 3D colliders.
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit[] hitInfo = Physics.RaycastAll(ray.origin, ray.direction);
foreach (RaycastHit h in hitInfo)
{
if (h.collider.name == "UncleRayTarget")
{
//do something
}
}
I am not able to test this right now, but it should do the trick.
Thanks! it works excellently :) now I'm just wondering if there is a way to generate a collider on each sprite that makes up the map and if it is going to be a problem that each hex has name generated depending on where they are in the world?
It is possible, depending on what you really need. :) You can make editor script, that will find and add Collider component on all your hex sprites and rename them accordingly. Later on in your RayCast method expect collider.name for sprite you need... Again, depending on what you need...
Yeah fair enough, I'll have to do some more research, probably by asking more questions, and work it all out, thanks!
Your answer
Follow this Question
Related Questions
Range not working c# - shooting script using raycast 0 Answers
Moving dotted guide line 0 Answers
How to stop raycast at first object hit? 2 Answers
Do touch on point where ray hits 0 Answers
How to store field of hexagons 1 Answer