- Home /
simple mouse raycasting problems
I am having a problem with trying to set up a raycast. The raycast will ideally go from my mouse to a button, and when I press the left mouse trigger the button will trigger. But for some reason, my ray isn't being drawn. Any assistance would be greatly appreciated. Here is my current code. It has been three days can anybody help me?
private void Update() { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); //Debug.Log(ray); RaycastHit hit; if (Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit, Mathf.Infinity)) { UnityEngine.Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * hit.distance, Color.yellow); UnityEngine.Debug.Log("hit it"); } else { UnityEngine.Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * 1000, Color.magenta); UnityEngine.Debug.Log("missed it"); } }
Answer by iJuan · May 13, 2018 at 05:45 PM
You are never using your mouse's position Ray (You are just declaring it).
Replace your Phyisics.Raycast
with Physics.RaycastAll
foreach (RaycastHit hit in Physics.RaycastAll(ray)) {
UnityEngine.Debug.DrawRay(ray.origin, ray.direction * hit.distance, Color.yellow);
}
An approach more similar to yours would be:
RaycastHit[] hits = Physics.RaycastAll(ray);
if (hits.length > 0)
UnityEngine.Debug.DrawRay(ray.origin, ray.direction * hit.distance, Color.yellow);
else
UnityEngine.Debug.DrawRay(ray.origin, ray.direction * 1000, Color.magenta);
Your answer
![](https://koobas.hobune.stream/wayback/20220612162344im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Want to move object slowly to where the mouse clicks? 1 Answer
OnMouseUp() not working like meant 1 Answer
C# mouse Raycast question 3 Answers
Raycast2D always "remembers" it's last hit 2 Answers
Translate Mouse to Worldspace 0 Answers