Search code examples
c#unity-game-engineraycasting

How can I offset my raycast slightly to the right?


I'm casting a raycast from the mouse cursor to a point. Then I would like to cast another almost identical raycast, with the only difference being that it should have a slight offset to the right.

I'm doing this in Unity2D, what's the best way to go on about this?

It has to take the mouse position into account, so that the direction it's casting to is offset to the right of the cursor's position.


Solution

    1. Make a direction vector, you already have this, because this should be the second parameter of your ray. (In unity we define a ray by a starting point and by a direction, the direction is your direction vector)
    2. Make a normal vector from this direction vector.

      If your direction vector coordinates are v1(A; B) then your normal vector is vNormal(B; -A)

    3. And now you offset your original start point (where the ray is heading from to its direction), by the following formula point += vNormal.normalized * OffsetValue;, assuming this exists public float OffsetValue = 5.0f;

    Some visuals: enter image description here So, if we move your mousePos by the green line normalvector(the yellow line direction vector), we can shoot a ray like the purple line. Expected result: enter image description here

    Update:

    Is this the result you want? enter image description here Because in this case, you offset the hitpoint the same way you would offset the mousePos, and then calculate a new direction for your ray Vector2 newDir = offsettedHitPoint - mousePos;