This is the code for Raycast:

RaycastHit hit;
Vector3 direction = transform.forward;

Debug.DrawRay(transform.position, direction * 200f, Color.red, 0.1f);

if(Physics.Raycast(transform.position, direction * 200f, out hit, 200f)) {
    if(hit.transform.tag == "Enemy") {
        // do something with enemy  

I'm shooting the ray to in front of the object, but it's not quite working to me.

These are the screenshots:

enter image description here

enter image description here

As you can see above second picture, shot the ray to forward, but actual ray wasn't forwarded.

I also rotated the ray z axis 90 or -90 degree, but stil not working. (Actually I tried to rotate each axis 90 and -90, but nothing seems work)

Vector3 direction = Quaternion.Euler(0, 0, 90) * transform.forward;  // Doesn't work
Vector3 direction = Quaternion.Euler(0, 0, -90) * transform.forward;  // Doesn't work either

What am I missing?

  • \$\begingroup\$ Well then straighten your shooter :) \$\endgroup\$ – Engineer Sep 19 '17 at 8:40
  • \$\begingroup\$ @ArcaneEngineer It is straightened \$\endgroup\$ – modernator Sep 19 '17 at 12:02
  • \$\begingroup\$ Hmm... it's tough to say why this would happen with the given info. Transform.forward reliably does what it's meant to, so it could be that your object's visual is rotated relative to its coordinate system (can you confirm whether your transform gizmo is in local or global coordinates in the screenshot above?) or that the ray-firing script is running on a different object, reflecting its transform instead of the flashlight's. \$\endgroup\$ – DMGregory Sep 19 '17 at 12:03
  • \$\begingroup\$ @DMGregory I just checked my flashlight and just saw that x axis was pointing the bottom. I made a model from Blender and looks like it's kind of axis problem that both are using different axis system. I have to find to fix this, thanks. \$\endgroup\$ – modernator Sep 19 '17 at 14:18
  • \$\begingroup\$ Are you using the Blender Unity rotation fix add-on for blender? answers.unity3d.com/questions/319802/… \$\endgroup\$ – Coburn Sep 19 '17 at 18:09

I solved this problem by check "Experimental Apply Transform" option when export as FBX my models.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.