- Home /
Raycast help
I'm trying to code a raycast gun heres the code I sort of got.
function Update () {
// Put this in your update function
if (Input.GetButtonDown("Fire1")) {
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
if (Physics.Raycast (ray, hit, 100)) {
print ("Hit something");
}
}
}
but it dosn't seem to print anything on the debug line after I press the fire button in front of an object with a collider :/ what am I doing wrong?
Just want to confirm: this is attached to your player, right?
Answer by DaveA · Jun 28, 2011 at 10:00 PM
You know this will only detect things if the mouse pointer is over them, right? So mouse-over something with a collider on it that's not too far away and hit the Fire1 button, it should print.
How would I have my mouse set in the middle of the screen like most shooter games then? because my mouse can move freely in the game.
Screen.lockCursor = true. Please do not ask new questions inside an existing one, this way other users who have the same problem won't find their solution.
Your answer
![](https://koobas.hobune.stream/wayback/20220612124742im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How does my raycast work? 1 Answer
Beginner to raycasting: making a gun 1 Answer
Raycast gun 2 Answers
Do raycasts only collide with colliders or can I detect a hit through something else? 2 Answers
Following Terrain Height? 2 Answers