In this post I will guide you to create raycast2D so that enemies can move on the terrain as shown below without falling down. And let's get started.
Join the channel Telegram belong to AnonyViet 👉 Link 👈 |
RAYCAST2D
Here Raycast 2D is a node: Query the object intersecting the ray means Raycast 2D is a ray and this ray is used to query the object when intersecting with the ray
ENEMY
Next is the enemy you enter the enemy's scene
Find yourself raycast2D
And like this
Here you don't use the mouse but use the right arrow key to move it to the edge. collsionshape
And almost exposed like me
On the properties side pay attention to yourself Enable and Cast to
live Enabled You click to choose for yourself and raycast will be green
LIVE cast to part y you cast it near the enemy
As in the picture, this enemy is too small so I will adjust the scale. raycast wall 0.5, 0.5
And after adjusting the scale, you also have to adjust the other parts.
Next we will code for it.
And Coding for me
Below if is_on_wall
You add for me is
if $Raycast2D.is_collding == false:
vitri = vitri * -1
Here $Raycat2D is to call raycast2d || is_collecting is the command: Returns whether any object is intersecting the vector ray but here we set = false which means it will not intersect with anything.
And vitri = vitri * -1
here means the enemy will move backwards when on the terrain that I mentioned at the beginning of the article
And you notice when it has moved back, this raycast2D does not move back anymore, so we need to adjust it.
You add $RayCast2D.position.x *= -1
enter if is_on_wall and raycast collection Please
This is the command to help Raycast 2D can be redirected and you can apply it to other nodes like collsionshape etc.
It is done
And remember to delete *delta let's go
If the code does not run, use the code below.