Raycasting is in world direction, not local?

Hi all,

I created a script to make a crosshair that changes color when a raycast hits an object with a different tag ("Friend" or "Enemy") That worked fine, however the raycast shoots forwards on the world axis, so if the object is forward to me on the world axis, no matter where I face, the crosshair changes color.

The object I have it attached to is the camera on a FPS character (So the parent rotates on the x axis, and it rotates on the y). Here's part of my script:

var crosshairRange = 200;

private var hit : RaycastHit;
private var facingDirection = Vector3.forward;

function Update () 
{
    if (Physics.Raycast(transform.position, facingDirection, hit, crosshairRange))
    {
        if (hit.collider.gameObject.CompareTag("Enemy"))
        {
            enemyHit = 1;
        }

etc.

My guess is the problem is with either the private variable 'facingDirection' or 'transform.position' bit , but I don't know what the problem is.

Any help would be appreciated!

It's facing direction, yes

Use transform.forward instead of Vector3.forward for the world space forward vector of your object

On top of that, you're only setting it once, which would be fine if it were in local space, but you'll need to move the facingDirection assign into Update now

You don't need the variable facingDirection. Just use transform.forward, which is in world space.

http://unity3d.com/support/documentation/ScriptReference/Transform-forward.html

Looks like an old post but I ran into the same problem. Above answer works great but if you MUST need vector3 you can do the following and get same outcome. Maybe this will help someone.

Instead of using *transform.forward* you can use **transform.TransformDirection(vector3.forward)** as shown below.

Physics.Raycast(transform.position, transform.TransformDirection(Vector3.forward), out hit);