Trouble with Ray & Raycasting and AddForce()

In my code, when you click on the screen, the sphere starts in the direction of the finger tap. It uses raycast. The sphere is launched only if the raycast hit contains information about the rigidbody-body. However, if I shoot raycast somewhere in the sky, then this code, in fact, should be ignored. However, no, the sphere will spawn somewhere above the stage and fall, although this should not have happened. What is the problem?


private IEnumerator SpawnSphere(Vector2 position)
    {
        yield return new WaitForSeconds(0.1f);

        if (Input.touchCount == 0)
        {
            GameObject shell = Instantiate(shellPrefab) as GameObject;
            Ray ray = Camera.main.ScreenPointToRay(new Vector3(position.x,position.y));
            RaycastHit hit;

            if(Physics.Raycast(ray, out hit))
            {

                if (hit.rigidbody != null)
                {
                    shell.GetComponent<Transform>().position = transform.position;
                    shell.GetComponent<Transform>().LookAt(hit.point - transform.position);
   shell.GetComponent<Rigidbody>().AddForce((hit.point - transform.position), ForceMode.Impulse);

                }
            }
        }
        yield return null;
    }
}

Besides this, there is one more problem. See this line?

shell.GetComponent<Rigidbody>().AddForce((hit.point - transform.position), ForceMode.Force);

In this sphere code, a force is added that moves this sphere into a certain vector. However, the force varies depending on the distance to this vector! What should this vector (or other operation) be multiplied for, so that the sphere can be launched with the same force regardless of distance?


Hey there,

the solution to your first problem is, that you spawn the shell either way. You don’t check for a raycast hit before spawning it, and you don’t remove it when you don’t hit anything.
In case there is no hit the shell will spawn at the position given in the prefab and will not be further handled.

For your force problem you have 2 options:
either use Vector3.Clamp() to clamp the direction vector to a given length.

Or:

Use something like: (hit.point -transform.position)/Vector3.Magnitude(hit.point-transform.position)
This will normalize the vectors length to 1.

OR:

Use (hit.point -transform.position).normalized

Hope this helps.