My Raycast code has bad aim!

Hello my friends,
today I followed this tutorial to create objects (excuse me, I’m begginer), I made code same, but Raycast is casting badly.

On this screenshot I’m aiming on top of first left mountain and camera is on left down side of raycast, but other side is aiming somewhere to terrain. But it should Aim to mouse.position… Can you help me guys?


RaycastHit hit;
public GameObject Target;
private float raycastlength = 500;

// Update is called once per frame
void Update () {
	Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
	if(Physics.Raycast(ray, out hit, raycastlength)){
		if( == "Terrain"){

				Debug.DrawRay(transform.position, hit.point, Color.white, 0.5f, true);
				GameObject TargetObj = Instantiate(Target, hit.point, Quaternion.identity) as GameObject; = "Target Instantieted";

You’re drawing the white line in a different place than the raycast. In other words, raycasts are always invisible, and what you’re seeing isn’t where the raycast is going. DrawRay is tricky to use.

You should be able to find examples in here (Unity Answers) of drawing a ray. The “mouse cast” is very common. But the ray is only testing, you can skip that line. Do things get Instantiated in the right spot? If the tutorial really has that line in it – well, 90% of the internet is wrong. Why should tutorials be an exception?


change your debug line to:

Debug.DrawRay(transform.position, hit.point-transform.position, Color.white, 0.5f, true);

The method Debug.DrawRay takes the direction of the ray as second parameter, not the end point of the ray. So you have to use the vector which points from the start of your ray(camera) to your target. Assuming that your script is attached to the camera of course.


Vector b points to your camera and vector a points to your target. The direction from b to a is vector red which you get by calculating a-b


Take a look in some basic vector calculating tutorials and linear algebra tutorials.