Randomizing Angles when firing bullets in 3D

Godot Version

4.2.1

Question

I got this code for creating a bullet that shoots in a straight line in 3D:

		var tank_bullet_instance = tank_bullet.instantiate()
		var bullet_create_at_position = tank_cannon.global_transform.origin
		var target_position = hitMarker.global_transform.origin
		var bullet_speed = 50
		var bullet_direction = bullet_create_at_position.direction_to(target_position)
		tank_bullet_instance.velocity = bullet_speed * bullet_direction
		tank_bullet_instance.look_at_from_position( bullet_create_at_position, target_position )
		get_tree().get_root().add_child(tank_bullet_instance)

The bullet travels in a straight line to its target_position, but now, I want to have some deviation. Suppose you shoot 100 bullets like a machine gun, instead of them landing on the same spot. I would like them to travel to the intended target_position but they will have +/- several degrees. The “danger zone” will be like a cone instead of a straight line. How to add this “random” angle here in 3D?

I would just add a random vector to the target based on distance.

var distance = (target_position - position).length()
tank_bullet_instance.look_at_from_position(
   bullet_create_at_position, 
  target_position  + some_random_unit_vector * distance * some_weight
   )
1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.