how do i throw a grenage in a 3D enviroment?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By master8829

I am working on a 3D forst person shooter and now I’m stuck on grenades i can figure out how to create a grenade and animate it but not how to throw it I can’t figure out the math and all youtube tutorials I found were outdated in 3.5. the grenade is a rigid body
all and any help is appreciated .

:bust_in_silhouette: Reply From: Zylann

The concepts haven’t changed much since Godot 3. Assuming you already have some code setup in a script to detect input for throwing the grenade, here is one way it could be done:

First create a scene for the grenade. Create the following hierarchy:

RigidBody3D
|-CollisionShape3D <-- with a sphere shape roughly the same size as the model
|-MeshInstance3D <-- visual of the grenade. Could be a sphere

You can add more stuff to the grenade but for the sake of the example I keep things minimal. The root must be a RigidBody3D to allow the grenade to bounce into the environment.

Next, in your player script, you can add this code:

# Import the grenade scene
const GrenadeScene = preload("grenade.tscn")

# Call this when the player presses the button to throw a grenade
func throw_grenade():
	# Get camera position and direction
	var camera := get_viewport().get_camera_3d()
	var camera_transform := camera.global_transform
	var forward := -camera_transform.basis.z
	
	# Spawn grenade sligtly in front of the camera,
	# with some added velocity so it moves forward.
	# The offset is also to make sure it doesn't collide with the player throwing it.
	var grenade : RigidBody3D = GrenadeScene.instantiate()
	grenade.position = camera_transform.origin + forward * 0.5
	grenade.linear_velocity = forward * 10.0
	var level := get_parent()
	level.add_child(grenade)

It’s a very basic example but there are infinite ways in which this can be tweaked.