Kinematicbody2d body moving on its own

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By grey_lotus
I'm working on the mechanics for a character and I ran into a problem. Two problems actually. 
  1. The character suddenly begins to move on its own after leaping
  2. I can’t seem to disable the character’s jump when it’s already in the air (jumping or leaping)
    Here’s the code snippet:
if Input.is_action_just_pressed("jump"):
	velocity.y = -jump
	print("jumped")
if Input.is_action_pressed("leap"):
	leap_power += 10
	print("leap charging ")
	print (leap_power)
	if leap_power > MAX_LEAP_POWER:
		leap_power = MAX_LEAP_POWER
		
if Input.is_action_just_released("leap"):
			velocity = Vector2(30, -leap_power)
			leap_power = 200
			print("leaped")
	
move_and_slide(velocity)
:bust_in_silhouette: Reply From: njamster
  1. The character suddenly begins to move on its own after leaping

Your code doesn’t apply any friction, i.e. once you set the velocity-vector to a value other than zero, your character will move into that direction without slowing down.
Take a look at this question to get an idea of how to implement friction.

I can’t seem to disable the character’s jump when it’s already in the air (jumping or leaping)

Right now, you’re onl checking if the jump-key was just pressed without any further constraints. Instead only allow jumping when on the floor:

if Input.is_action_just_pressed("jump") and is_on_floor():
    velocity.y = - jump

In order for this to work, the floor has to have a CollisionShape2D.

For further inspiration, I highly recommend you take a look at the demo project. You can download it by starting Godot, but instead of selecting a project from the list, switch the tab to “Templates” and search for “2D Platformer Demo”. Once you installed it, it will appear in your project list and you can play around with it.

Yeah. I fixed it. Thank you.

grey_lotus | 2020-02-04 15:52