Problem with raycasting
Hello gents, i have been having a minor issue here lately, while the code executes alright, it does not seem to be working properly
private void PlaceTurret()
{
if (Input.GetMouseButton(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); // Initialize the ray // reference in document
RaycastHit2D[] hits = Physics2D.RaycastAll(ray.origin, ray.direction); // Raycast points to objects stored in array
if (hits.Length > 0 && hits[0].collider != null )
{
GameObject turret_ = BuildManager.Instance.Getturret; // Get the turret;
turret_.transform.position = hits[0].collider.gameObject.transform.position; // Make the turret position equal to position that was clicked
if ((hits.Where(x => x.collider.gameObject.tag == "Turret"
|| x.collider.gameObject.tag == "Path").Count()) > 0) // If turret is placed on another turret or path, the user cannot place it
{
return;
}
else
{
BuildTurret(BuildManager.Instance.Getturret); // Build the turret
}
}
}
}
}
I have a script that uses raycasts to detect when i am clicking on a turret or the path, while it does place the turret on the map, it isn't placed where it is supposed to be placed, rather it is being placed much further away than where i am clicking even though the raycast isn't hitting anything.
If anyone has a way to make the raycast point better it would be helpful
Answer by NoBrainer-David · May 13, 2017 at 04:04 PM
I think your problem is in this line:
turret_.transform.position = hits[0].collider.gameObject.transform.position; // Make the turret position equal to position that was clicked
You are not using the point you clicked, instead, you are using the position of the object that was hit. This is not necessarily the same thing. You can use hits[0].point instead. This is the point in world-space where the ray and the collider intersect.
Yeah i was thinking the same thing, ill change the code and see if it works
Answer by KingB · May 15, 2017 at 07:27 AM
Ok i've tried adjusting the origin of the raycast but they are still being placed in the same distance
RaycastHit2D[] hits = Physics2D.RaycastAll(new Vector2(ray.origin.x + 0.5f, ray.origin.y + 0.5f), ray.direction);
The origin of the raycast is not the problem.
Can you show us what your build turret function does? Why are you not passing in the object you used above where you set the position on?
Your answer
![](https://koobas.hobune.stream/wayback/20220612121922im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
(Raycasts) C# Why am I shooting myself? 0 Answers
Is there any way how to do raycasts like this? 0 Answers
Strange Raycast problem 0 Answers
Scripting Errors 1 Answer
Unity 2D Raycast Collision Detection 1 Answer