x


Using RayCast to Get Mouse Input

I am really frustrated, so much so that I am going to ask this last question and walk away from the computer and wait. I'm trying to use raycasts to get the current mouse position at a click. For now, I'm instantiating an object as a debugger. Here's my code:

var particle : GameObject;
function Update () {
if (Input.GetButtonDown ("Fire1")) {
// Construct a ray from the current mouse coordinates
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray)) {
// Create a particle if hit
Instantiate (particle, transform.position, transform.rotation);
}
}
}

Now, when I play the game, when I click, it instantiates the object right at the camera's position. What am I doing wrong? Any and all help appreciated.

Elliot Bonneville

more ▼

asked Mar 22, 2010 at 01:09 AM

e.bonneville gravatar image

e.bonneville
6.3k 253 226 283

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

You say to instantiate at transform.position, which is the camera's position (I'm assuming your script is attached to the camera). You need to create a RaycastHit variable and use the position where the raycast actually hits.

var hit : RaycastHit;
if (Physics.Raycast (ray, hit)) {
// Create a particle if hit
Instantiate (particle, hit.point, transform.rotation);

That will still use the camera's rotation; probably you want to use Quaternion.identity instead.

more ▼

answered Mar 22, 2010 at 01:45 AM

Eric5h5 gravatar image

Eric5h5
112k 56 203 695

Booo... I would give the next plus, but I still can't. Any way - thanks :)

Feb 14, 2013 at 03:05 PM Astroni

Indeed, helpful.

Nov 16, 2011 at 06:20 PM cj_coimbra

Thanks. I spent all night on that!

Mar 22, 2010 at 06:52 PM e.bonneville

Would give 20 votes... If I could!

Mar 22, 2010 at 06:52 PM e.bonneville

come on people! upvote it so it gets to 20!

Oct 24, 2011 at 11:49 PM Jibidiah
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x2949
x1623
x1473
x368

asked: Mar 22, 2010 at 01:09 AM

Seen: 30376 times

Last Updated: Feb 14, 2013 at 03:05 PM