0 votes

I was trying to implement the RayCast2D node to detect collisions, in order to avoid ledges. The sprite would change its direction once it detects a ledge.

My code:

    extends KinematicBody2D

const GRAVITY=20
var SPEED=50
var motion=Vector2()
const UP=Vector2(0,-1)
var flag=1
func _physics_process(delta):
    motion.y+=GRAVITY

    if is_on_wall() :
        $RayCast2D.position.x*=-1
        SPEED*=-1

    if $RayCast2D.is_colliding()==false:
        SPEED*=-1
        #print('not detected')
        $RayCast2D.position.x*=-1
        flag=0
    else:
        SPEED*=1
        #print('detected')
        $RayCast2D.position.x*=1
        flag=1
    if SPEED<0 or flag==0:
        $Sprite.flip_h=true
    else:
        $Sprite.flip_h=false

    print(SPEED)
    motion.x=SPEED
    $Sprite.play("walk")
    motion=move_and_slide(motion,UP)
    pass

The code works fine, as the sprite can detect ledges and avoid them. But when it gets to an upward slope, the sprite changes its direction again after climbing half of it. It doesn't make any sense, as the SPEEDwon't change as long as it doesn't detect a ledge. Is there something wrong with the code?

in Engine by (21 points)

Please log in or register to answer this question.

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.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.