2

I have two arbitrary points V1 and V2. I define a ray from V1 to V2 and I want to find the exact place that the ray hits the plane. When I run my code, the hit position is landed on wrong position! As you can see the green sphere shows the ray collision position which is not aligned with V1 and V2.
enter image description here

using UnityEngine;
using System.Collections;
public class RaycastLearning : MonoBehaviour {

// Use this for initialization
Vector3 v1;  
Vector3 v2; 
float MoveToLeft = 5f;
void Start () {
    GameObject plane = GameObject.CreatePrimitive (PrimitiveType.Plane);
    plane.transform.rotation = Quaternion.AngleAxis (90f, Vector3.right);
    plane.transform.position = new Vector3 (MoveToLeft, 0, 5);

    v2 = new Vector3 (MoveToLeft, 0f, -10f);
    v1 = new Vector3 (MoveToLeft, 0f, 10f);
    GameObject SV1 = GameObject.CreatePrimitive (PrimitiveType.Sphere);
    SV1.transform.position = v1;
    SV1.name = "SV1";
    GameObject SV2 = GameObject.CreatePrimitive (PrimitiveType.Sphere);
    SV2.transform.position = v2;
    SV2.name = "SV2";

    RaycastHit r = new RaycastHit ();
    if (Physics.Raycast (v1, v2, out r, 20f)) {

            GameObject sphere = GameObject.CreatePrimitive (PrimitiveType.Sphere);
            sphere.transform.position = r.point;
            sphere.transform.position = new Vector3 (r.point.x, 0, r.point.z);
            Material MaterialCol = new Material (Shader.Find ("Diffuse"));
            MaterialCol.color = Color.green;
            sphere.GetComponent<Renderer> ().material = MaterialCol;
            sphere.transform.localScale = 0.5f * Vector3.one;
        }

}
// Update is called once per frame
void Update () {

}
}

It is very interesting for me because when I place the plane in (0,0,5), V1 in (0,0,10) and V2 in (0,0,-10) it returns the correct point but in other angles and placement they don't return correct points.

Could you help me to find the problem?

1 Answer 1

6

You are trying to do a Raycast from points v1 to v2 but, but instead of passing (point,direction,out RaycastHit, distance) as the arguments, you are passing (point,point, out RaycastHit, distance) in the following line:

if (Physics.Raycast (v1, v2, out r, 20f)) {

The second parameter of a Raycast, in this instance, is a direction Vector, not a point in space, as per the API. So unity is treating your v2 variable as a direction vector. To get a direction vector from v1 to v2, simple subtract v1 from v2. For example:

Vector3 delta = v2 - v1;
RaycastHit hitInfo = new RaycastHit ();
if (Physics.Raycast (v1, delta , out hitInfo, delta.magnitude)) {}

Alternatively, you could simply do a linecast:

RaycastHit hitInfo = new RaycastHit ();
 if (Physics.Linecast (v1, v2 , out hitInfo)) {}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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