- Home /
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!
Answer by Mike 3 · Oct 27, 2010 at 06:44 AM
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
That worked great for me except it's not rotating on any of the other axis. As in when I look up it won't rotate up, just sort of slides up but aims forward.
Answer by Jessy · Oct 27, 2010 at 06:45 AM
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
Answer by FlightOfOne · Jul 01, 2014 at 06:30 AM
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);