Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Send a raycast from an object's position in the direction of it's rotation

Discussion in 'Scripting' started by glde, Jul 4, 2022.

  1. glde

    glde

    Joined:
    Jan 30, 2022
    Posts:
    8
    Hi, I have been having trouble over the past few hours figuring out how to orient a raycast in the direction of a quaternion. I'm trying to check in the direction an object is rotated from its position. I've tried using euler angles, but must be doing something wrong if they are the solution. Here's what I've been trying:
    Code (CSharp):
    1. Physics.Raycast(object.transform.position, object.transform.position + object.transform.eulerAngles, out hit, 100)
    and I've been testing it with this in OnDrawGizmos():
    Code (CSharp):
    1. Gizmos.DrawLine(object.transform.position, object.transform.position + object.transform.eulerAngles);
    It mostly seems to point in a random direction, and doesn't move smoothly with the object's rotation. I'm not sure what else to try.

    Thank you!
     
  2. passerbycmc

    passerbycmc

    Joined:
    Feb 12, 2015
    Posts:
    1,741
    i may not be understanding your question, but pretty sure you want object.transform.forward which returns you a vector facing down the objects local z axis
     
  3. glde

    glde

    Joined:
    Jan 30, 2022
    Posts:
    8
    That's not quite what I was going for, I should have explained better. In essence, I'm trying to get a vector3 which represents a point in space that, if you drew a line between it and the origin, would represent the rotation of the object (or the direction that object is facing).
     
  4. passerbycmc

    passerbycmc

    Joined:
    Feb 12, 2015
    Posts:
    1,741
    still think you might want your origin point + transform.forward in that case, adding Euler angles to a positions makes zero sense, the angles have nothing to do with position
     
  5. Rotary-Heart

    Rotary-Heart

    Joined:
    Dec 18, 2012
    Posts:
    813
    Depending on what you want to do, forward will definitely allow you to do what you want. This is guessing that the forward is where your object is facing, but you can also use quaternion to rotate your vector.

    object.transform.rotation * object.transform.position


    Note that the order is important for multiplying vector and quaternions (matrix multiplication)
     
  6. glde

    glde

    Joined:
    Jan 30, 2022
    Posts:
    8
    I understand now, thank you so much!