x


Raycast questions

I have a few questions about raycasting I'm using a raycast script for my gun heres the code.

    Screen.lockCursor = true;
    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");
        }
    }
}

I have a few questions though. 1. How would I use a texture as a crosshair in the center of the screen? 2. How would I make the enemys react to the raycast hitting them would it be something like "OnRaycastEnter()"? 3. How would I make the raycast go in the direction of the crosshair texture instead of the mouse?

more ▼

asked Jun 29 '11 at 02:21 AM

twoface262 gravatar image

twoface262
129 40 53 55

formatted your code for you- make sure when you post a question that your code is readable.

Jun 29 '11 at 02:51 AM testure
(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

1) A texture as a crosshair is just a GUITexture in the middle of your screen. simple as that. Here's how you use it:

http://unity3d.com/support/documentation/Components/class-GuiTexture.html

2) The answer is in the code you posted. if your raycast hits something, it will drop into the conditional statement that says print("Hit something"). from there you can access the object that it hit using hit.collider (what you do with it after that is up to you). Here's how you use raycasting:

http://unity3d.com/support/documentation/ScriptReference/Physics.Raycast.html

3) use Camera.ViewportPointToRay to create your ray:

http://unity3d.com/support/documentation/ScriptReference/Camera.ViewportPointToRay.html

You'll notice that I linked the Unity docs in every answer. All of your questions were solved by one source of information. Please read the unity docs, you will learn a ton from it.

more ▼

answered Jun 29 '11 at 02:55 AM

testure gravatar image

testure
4.2k 20 25 48

Thank you those where very helpful.

Jun 29 '11 at 03:04 AM twoface262
(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:

x2210
x1537
x655
x110

asked: Jun 29 '11 at 02:21 AM

Seen: 1454 times

Last Updated: Jun 29 '11 at 03:04 AM