0 votes

I tried using RayCast2D to make the enemy walk in the platform without falling, but it don't works, he stay idle and the sprite don't stop flipping. (And it's enable in property editor)

This is the link for you can download my project: https://drive.google.com/open?id=1sAGQKQhw5brKdYFizBf_jIApq-HmuA05

This is the script of the enemy:

extends KinematicBody2D

const GRAVITY = 10
const SPEED = 30
const FLOOR = Vector2(0 , -1)

var velocity = Vector2()

var direction = 1

func _ready():
pass

func physicsprocess(delta):
velocity.x = SPEED * direction

if direction == 1:
$AnimatedSprite.fliph = false
else:
$AnimatedSprite.fliph = true

$AnimatedSprite.play("walk")

velocity.y += GRAVITY

if isonwall():
direction = direction * -1
$RayCast2D.position.x *= -1

if $RayCast2D.is_colliding() == false:
direction = direction * -1
$RayCast2D.position.x *= -1

velocity = moveandslide(velocity, FLOOR)

asked Dec 31, 2019 in Engine by Snayk (21 points)

1 Answer

0 votes

I looked at your project and I found two issues:

  1. The Raycast2D is never colliding because in your test_area tilemap, you need to enable collision layer 1 b/c your raycast is using mask 1. This will get the enemy to start moving left to the ledge and turn okay.
  2. When the enemy hits the wall, it will be stuck there, flipping indefinitely. One way to fix this is to add a short delay between the next wall check. You can add a timer node to your enemy with a 0.5 s time and a flag that gets checked before flipping the direction.

I updated your enemy code:

extends KinematicBody2D

const GRAVITY = 10
const SPEED = 30
const FLOOR = Vector2(0 , -1)

var velocity = Vector2()

var direction = 1
var wall_wait = false

func _ready():
    pass


func _physics_process(delta):
    velocity.x = SPEED * direction
    velocity.y += GRAVITY

    if direction == 1:
        $AnimatedSprite.flip_h = false
    else:
        $AnimatedSprite.flip_h = true

    $AnimatedSprite.play("")

    if is_on_wall() and !wall_wait:
        direction = direction * -1
        $RayCast2D.position.x *= -1
        wall_wait = true
        $Timer.start()

    if $RayCast2D.is_colliding() == false:
        direction = direction * -1
        $RayCast2D.position.x *= -1

    velocity = move_and_slide(velocity, Vector2.UP)

func _on_Timer_timeout():
    wall_wait = false

I also made these changes and re-shared the project with you on google docs.

answered Dec 31, 2019 by 2D||!2D (383 points)
edited Dec 31, 2019 by 2D||!2D
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.