need help converting world coords to vector3 direction value

Hey all.

I’m having trouble getting the vector3 direction value from a set of world coordinates. This is for a 3rd person shooter. Basically I want the character to shoot at where I’m pointing with the cross hairs. What I’m doing is:

  1. A raycast from the camera position directly ahead. This gives me the hit point where the user is aiming with the cross hairs.

  2. Then I’m doing a 2nd raycast from the character towards the direction of the hit point of the first ray cast.

The problem is that the raycast function takes a vector3 direction as its 2nd argument, not a vector3 point.

What I need to do is convert the world space coordinates from the first raycast hit point, in to a vector3 direction value that I can feed in to the 2nd raycast. Can someone tell me how to do this? :slight_smile:

Let me know if this makes sense and thanks in advance.

-M

what you need to do is using one ray cast from your gun and use transform.forward * unit distance as direction vector.

Hi Aubergine, thanks for the response.

I’m not sure what you mean in the second part of your answer. Such as this:

Physics.Raycast(gunPosition, gunTransform.forward * (dont know what to add here), rayCastHit);

Do you know how I can get the direction vector from the world coordinates of the hit point. I don’t know how to do this.

Thanks again :slight_smile:
-M

The direction vector pointing from a point A to a point B can be found by subtracting them (in the correct order!):

directionAtoB = pointB - pointA;

Hey Aubergine, thanks for that, works like a charm :slight_smile:

I should have come here hours ago. I wasted about half a day trying to figure that out, haha. Well at least I had a good read of the the documentation anyway,

Much appreciated mate :smile:
-M

You can also use the following, if it helps;

shootDir = transform.TransformDirection (Vector3.forward);
if (Physics.Raycast (transform.position, shootDir, out hit, weap.range)) {
.
.
}

TransformDirection, gives you a relative direction to the transform.

Great, Thanks again :smile: