- Home /
How to throw a RigidBody in the direction of Mouse Pointer (3D)?
Hello everyone, I need help!! so I am creating a 3d game with bunch of obstacle(cubes) in it. player will shoot a bullet(gameObject). Bullet will spawn at the position of player. my main camera is like third person perspective.
now my problem is I can add force in forward direction, but I need to throw my bullet in the direction of my mousePointer. How can I do it. If you want my scripts or screenshot of how my game looks like, please give me ur email and I will surely send.
Please Help!!
Answer by qobion · Apr 10, 2019 at 06:57 AM
Camera cam;
Rigidbody r;
Vector3 direction = cam.ScreenPointToRay(Input.mousePosition);
r.AddForce(direction * 100);
Answer by yozaak · Jan 09 at 01:44 PM
Would just like to modify code shared by @qobion a bit.
Camera cam; Rigidbody r;
//cam assignment cam = GameObject.Find("Main Camera").GetComponent();
//As ScreenPointToRay return a Ray type, it is required to use Ray.direction to get Vector3 direction
Vector3 direction = cam.ScreenPointToRay(Input.mousePosition).direction;
r.AddForce(direction * 100);
No problem. Just adding this for any future reference. I myself was searching for a solution yesterday when I stumbled on this thread.
Cheers !
Your answer
Follow this Question
Related Questions
Third-person mouse based-movement is blocked by edges of screen? 0 Answers
My mouse pointer is slow 3 Answers
How to throw a rigidbody toward the mouse? 1 Answer
What is the best way to make an AI throw something 2 Answers
Throwing dice with the mouse 0 Answers