In the previous section, I showed you how to create the most basic enemy, in this part I will show you how to make the enemy move on a floating surface.
With the surface like above, I guarantee that when your enemy moves to one of the two outer corners, it will drop but usually in platformet games when it moves to the corner it will return like and hit the wall in the front part.
So in this section I will show you how to do this.
First, you add yourself a new node called RayCast2D (this is the node used to query for targets that collide with rays).
This is a raycast and I’m going to use it to check if I’ve reached the corner I’ll tell the enemy to turn around.
I’ll make it shorter and turn it on.
func _physics_process(delta): chuyendong.x = tocdo * huong_dichuyen chuyendong.y += trongluc chuyendong = move_and_slide(chuyendong,Vector2.UP) animation.play("dichuyen") if is_on_wall(): huong_dichuyen = huong_dichuyen * -1 scale.x = scale.y * huong_dichuyen if $RayCast2D.is_colliding() == false: huong_dichuyen = huong_dichuyen * -1 scale.x = scale.y * huong_dichuyen
Here, I only added 3 lines of code, not much more.
First, the if line:
- That I will call the raycast node and check if it is colliding with something, if not then I have reached the corner then come back.
- The remaining 2 lines are used to rotate the enemy.
- the line scale.x = … actually you can leave the if outside, but not in the function, but I don’t because to optimize it, I put it in the if statement, so it only runs when it happens. If you leave it out, it always runs -> what the result is, you can guess.
This is the result after I run the game.
How it works
If you do not understand, I will explain in more detail here.
Here is the enemy when it’s not out of the corner, and the Raycast it is colliding with the tilemap as shown in the image.
And here is the enemy, when it reaches the corner, you see the raycast has come out of the tilemap (the raycast collides at the sharp corner of the arrow), when it goes out, it won’t collide with anything Also, in the script, I added an if to check if it doesn’t collide, then go back.
So I have guided you through how to create the most basic character, in the next part it will be to move between levels, kill enemies.