Using ray cast does not produce reasonable results

I want to detect when i am hitting my planets with the LineRenderer between the two ships. So I cast a ray that travels on the same line as the line renderer shown in the images. Line renderer is colored yellow.

I this image if you see bottom left the console prints hit planet Earth.

In this second image you see from top that the line renderer is between the planets and also the ray casted. If you check bottom left you will see that the console prints that the ray hit Earth2 but visualy it does not look like so.

Here is the code I am using for my GameController object. It is empty game object btw and it should controll the ray casting and line renderer.

using UnityEngine;
using System.Collections;

public class GameController : MonoBehaviour 
{

	public GameObject spaceShipSelected;
	public GameObject spaceShip1;
	public GameObject spaceShip2;
	public float spaceShipSpeed = 6f;

	Ray energyRay;
	RaycastHit rayHit;
	bool hittingPlanet = false;
	GameObject planetHit;
	float planetRadius;
	LineRenderer energyBeam;
	Vector3 movement;
	Vector3 spaceShip1Pos;
	Vector3 spaceShip2Pos;

	const string HORIZONTAL_AXIS = "Horizontal";
	const string VERTICAL_AXIS = "Vertical";
	const string MOUSE_SCROLL_WHEEL = "Mouse ScrollWheel";

	void Awake ()
	{
		spaceShip1Pos = spaceShip1.transform.position;
		spaceShip2Pos = spaceShip2.transform.position;
		energyBeam = GetComponent<LineRenderer> ();
	}
	
	// Update is called once per frame
	void Update () 
	{
		if (spaceShipSelected != null) 
		{ 
			Debug.Log(spaceShipSelected.name);
			assignShipMovement();
		}

		UpdateEnergyBeam();
	}

	void assignShipMovement ()
	{
		float h = Input.GetAxisRaw(HORIZONTAL_AXIS);
		float m = Input.GetAxisRaw(MOUSE_SCROLL_WHEEL);
		float v = Input.GetAxisRaw(VERTICAL_AXIS);

		movement.Set(h, m, v);
		movement = movement.normalized * spaceShipSpeed * Time.deltaTime;

		spaceShipSelected.transform.position += movement;
	}

	void UpdateEnergyBeam ()
	{
		spaceShip1Pos = spaceShip1.transform.position;
		spaceShip2Pos = spaceShip2.transform.position;

		energyBeam.SetPosition(0, spaceShip1Pos);
		energyBeam.SetPosition(1, spaceShip2Pos);

		energyRay = new Ray(spaceShip1Pos, spaceShip2Pos);
		if(Physics.Raycast(energyRay, out rayHit, Vector3.Distance(spaceShip1Pos, spaceShip2Pos)))
		{

			planetRadius = Vector3.Distance(rayHit.collider.bounds.center, rayHit.collider.bounds.extents);

			Debug.Log ("I hit a planet: " + rayHit.collider.name);
		}
	}
}

Note: To be more clear, I made the spaceShipSelected set to the game object (grey boxes) I select collored in yellow when I press on one of the boxes.

Any reason why this happens?

Seems to be the typical mistake that’s done quite often.

You use a ray which takes start position and direction as arguments, both being vectors. But you’ve passed the position of the second spaceship as a direction.

Try to use spaceShip2Pos - spaceShip1Pos as the second parameter.