Throwing Objects (694476)

Hi everyone, I need help with something. I need to know solutions about how can I make the effect of throwing a ball when I click the screen and be able to move in that direction.

I want the exact same thing with the ball of this video:

I tried with this but the ball just doesn’t go to the direction of the mouse.

var mousePos = Input.mousePosition;
        mousePos.z = 0.1f;
        Vector3 screenPos = cameraMain.ScreenToWorldPoint(mousePos);
        var ball = (GameObject) Instantiate (ballPrefap);
        ball.transform.position = screenPos;


        ball.GetComponent<Rigidbody>().velocity = new Vector3(3,screenPos.y,screenPos.z) * 0.5f;

I cannot use ScreenPointToRay because I want to thrown balls also into the empty space, just like the video.

Thanks.

From the video, it looks like the ball is being instantiates at the mouse position, and then given a velocity equal to the direction from the camera’s position to the mouse position (with the mouse being a little forward from the camera).

To do that, try something like this:

ball.GetComponent().velocity = (screenPos - cameraMain.transform.position) * _someSpeedMultiplier;

That should give the ball a force in the direction from the camera to the mouse. You may need to increase “mousePoz.z” a bit if the angle is too steep. And you might want to use the “.normalized” version of that vector, or it will probably shoot faster when you’re closer to the edge of the screen.

1 Like

Throwing this out there as another option.

public GameObject prefab;
public Camera cam;
void Update()
{
   if (Input.GetMouseButtonDown(0))
   {
      Ray r = cam.ScreenPointToRay(Input.mousePosition);
           
      Vector3 dir = r.GetPoint(1) - r.GetPoint(0);

    // position of spanwed object could be 'GetPoint(0).. 1.. 2' half random choice ;)
      GameObject bullet = Instantiate(prefab, r.GetPoint(2), Quaternion.LookRotation(dir));

      bullet.GetComponent<Rigidbody>().velocity = bullet.transform.forward * 20;
      Destroy(bullet, 3);
   }
}
2 Likes

@dgoyette @methos5k awesome, It actually both solutions work perfectly. Thank you so much.

You’re welcome. Take it easy :slight_smile: