How to shoot bullets in platformer 2D with aim at mouse?

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

My gun already aims at the mouse, so i just need to shoot bullets, and i tried a lot of tutorials, but nothing worked. I am a beginner, and i still can’t code on my own. The character moves and the gun is attached to the character and it (the gun) rotates to the cursor position.

What do you mean nothing worked? Have you tried preloading the bullet scene and then instancing it?

exuin | 2021-04-21 17:47

There was a tutorial of this type and the first steps worked but in the end it didn’t work

DangerousScore | 2021-04-21 17:55

Can I see your code

exuin | 2021-04-21 19:29

:bust_in_silhouette: Reply From: Tato64

First you will need to decide what type of node you will use for the bullets.

Mainly you will choose from RayCast2D or RigidBody2D (or KinematicBody2D), they both have their advantages and disadvantages but basically:

For bullets that are very fast (think realistic levels of bullet speed) i would use a RayCast2D, this will be a “hitscan” bullet (This means the hit is registered where the raycast is colliding at the exact frame you shoot, there is nothing travelling)

For something like, lets say, a missile or a cannon shot, i would use RigidBody2D this would be a “projectile” (This means it is a physical body “launched” from the weapon and it travels across the map in the physical space) IMPORTANT: if you use this method and the projectile travels too fast, it may pass through objects, since it will be in front of the object in one frame and then have passed it in the next frame, there will be no frame in which the projectile and the object overlap, and therefore no collision detected.

For a RayCast2D, you would first create a raycast2D node as a child of the weapon (So it inherits its direction) and that’s pretty much it (Besides setting up the length of the “Cast_to” property, depending on how far you want the shot to travel)

With a RigidBody2D it is a bit more tricky, you will have to create the projectile in a different scene and then create and instance of it when you shoot. After that you would apply_central_impulse

Keep trying, you will figure it out, try to start small to get the hang of it and dont forget to google the terms i used here. Good luck!

I tried a lot of tutorials, and almost all of them were with Area2D, and from like 12 tutorials in just 1 the bullets showed but they didn’t shoot from the right position.

DangerousScore | 2021-04-23 11:43

:bust_in_silhouette: Reply From: Scavex

This video is very good and you’ll learn a lot. I reckon you want to achieve something similar to this

Thank you so much! It worked!

DangerousScore | 2021-04-23 12:00