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.
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?