Destroying the enemies
This content is not available in your language yet.
Raycasting
Section titled RaycastingOur enemies have had nothing to stop them so far, but it’s time for that to change, it’s time to give ourselves a way to destroy them!
To do this, we’ll be using something called a Raycast3D The easiest way to think about this, is that we’ll be sending out a laser, whenever we click we’ll see if this laser is hitting something. If it is, we’ll destroy it!
Which as you may be able to guess, will mean we’ll need to add something new to our Inputs. In case you’ve forgotten, in the top left, click Project -> Project Settings -> Input Map
Add a new Input called “Attack” and assign it to the Left Mouse Button.
Then, let’s head to our Character Scene.
-
As a child of our camera (To make sure it’s always facing the same direction as our camera) add a new Raycast3D node. You’ll now see a short blue line pointing downward in our character scene.
-
To get it pointing forward, in the inspector, set its Target Position to X: 0, Y: 0: Z: -20. If this doesn’t get it point in the same direction as your camera, change around the values until it does. The -20 here determines the range at which our Raycast3D will detect collisions, you’re welcome to adjust this value to be higher or lower to what feels right for your game.
-
Let’s head to our character script, and create a new export value to store our Raycast3D
@export var raycast:RayCast3D -
Then, in the func _input(event) function, let’s add a new if
if(event.is_action_pressed("Attack")):Here’s what we need to do after the player clicks:
- See if our raycast is colliding with anything
- See if what it’s colliding with is an Enemy
- Destory It
-
Steps 2 and 3 are easy enough, we’ve done both of those before. To check if the raycast is colliding with something, we’ll use:
if(raycast.is_colliding()): -
Then, we just need to do the last two steps.
if(raycast.get_collider().is_in_group("enemy")):raycast.get_collider().get_parent().queue_free() -
Giving us a final statement that looks like this:
if(event.is_action_pressed("Attack")):if(raycast.is_colliding()):if(raycast.get_collider().is_in_group("enemy")):raycast.get_collider().get_parent().queue_free()Important: Make sure you assign the RayCast3D in the inspector by dragging it from the scene tree into the box in the inspector!
Let’s test our game! We should now be able to destroy enemies by clicking on them! Although it’s a little difficult to aim for now… But don’t worry, We’ll be adding a reticule to help us in the next step.