How do I move a Collision2D in the direction of the mouse?

Godot Version

I’m using Godot V 4.4

Question

I’m trying to make a system where the player uses a ‘gun-like’ tool that shoots out 1 bullet each time a button is pressed, and when you shoot 3 times the player needs to reload.

Well, first off you don’t want to move a Collision2D, you want to move the object it is the collider for. What does your scene tree look like?

It looks like this:

I used a raycast for aiming, but when I try to use a rigid body for the ‘peas’, the bullets fall as soon as the scene starts.

Ok, so first off, you cannot have the bullet a child of the player. They will move with the player. They need to be spawned in the root of the tree or in the level.

Second, a RigidBody2D is affected by gravity. They are intended for things like grenades. For bullets you are better off using an Area2D for the bullet if it has a physical appearance on the screen.

1 Like

I tried what you said but its not working.

Here’s the scene tree:

And here’s the code:

So far I’m only testing with One of the ten bullets.

extends Node2D

@onready var aim: RayCast2D = $Aim
@onready var chip: CharacterBody2D = $"../Cassy"
@onready var _1: CollisionShape2D = $"Aim/Bullet 1/CollisionShape2D"


func _ready() -> void:
	_1.disabled = true
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	aim.look_at(get_global_mouse_position())
	aim.position = chip.position
	
	if Input.is_action_just_pressed("pipis"):
		print ("Bullet Shot")
		_1.disabled = false
		_1.velocity = 7000


You haven’t tried what @dragonforge-dev said in the first paragraph of the last reply and the previous reply.

Additionally, you shouldn’t keep all bullets within your Player scene. These should be instanced dynamically upon shooting.

Also, your code most likely produces some errors that you’re ignoring and not sharing here. Try to get rid of them, it will fix half your problems.

2 Likes

Is this what you meant?

extends Node2D

@onready var aim: RayCast2D = $Aim
@onready var chip: CharacterBody2D = $"../Cassy"

var bullet1
var col1

func _ready() -> void:
	pass
# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta: float) -> void:
	aim.look_at(get_global_mouse_position())
	aim.position = chip.position
	
	if Input.is_action_just_pressed("pipis"):
		print("{shoot}")
		bullet1 = Area2D.new()
		aim.add_child(bullet1)
		col1 = CapsuleShape2D.new()
		print(col1)
		bullet1.velocity.x = 7000

It says:

Invalid access to property or key 'velocity' on base object of type 'Area2D'