The player doesn't move on x axis although it responds with the animations and jump code.

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Dinoking

My game is a platformer but when I hit the right arrow key or left ones , the player doesn’t move as expected (although it jumps well). Also animation stops. I have tried to do a lot of things , even make a new project from scratch (although I copied and pasted the player script) . I think problem is with player script but I couldn’t find one :

The script:

extends KinematicBody2D


var velocity = Vector2()
var speed = 200
var max_speed = 100
const GRAVITY = 10

const FLOOR = Vector2(0, -1)
var on_ground = false

func _ready():
	pass

func _physics_process(_delta):
	
	
	
	if velocity.x == 0:
		$AnimatedSprite.play("Player_idle")
		$AnimatedSprite.speed_scale = 1
	if on_ground == false:
		$AnimatedSprite.play("Player_jump")
		$AnimatedSprite.speed_scale = 2
	
	
	if Input.is_action_pressed("ui_right"):
		#if on_ground == true:
		velocity.x = speed
		
		$AnimatedSprite.play("Player_run")
		$AnimatedSprite.flip_h = false
		$AnimatedSprite.speed_scale = 2
	elif Input.is_action_pressed("ui_left"):
		#if on_ground == true:
		velocity.x = -speed
		
		$AnimatedSprite.play("Player_run")
		$AnimatedSprite.flip_h = true
		$AnimatedSprite.speed_scale = 2
	
	if Input.is_action_just_pressed("damage"):
		$AnimatedSprite.play("Player_punch")
		$AnimatedSprite.speed_scale = 2
		
	else:
		velocity.x = 0
		
	
	if Input.is_action_just_pressed("ui_up"):
		if on_ground == true:
			velocity.y = -300
			on_ground = false
		
	velocity.y += GRAVITY
	if is_on_floor():
		on_ground = true
	else:
		on_ground = false
	
		
	velocity = move_and_slide(velocity, FLOOR)

maybe I am missing out something, pls help.

If you need project files, I 'd post that too.

:bust_in_silhouette: Reply From: magicalogic

The problem is in this block:

 if Input.is_action_just_pressed("damage"):
        $AnimatedSprite.play("Player_punch")
        $AnimatedSprite.speed_scale = 2

    else:
        velocity.x = 0 

If “damage” is not just pressed (which will be the case almost all the time since the player wont be damaging stuff constantly throughout the game), velocity along the x axis will be reset to zero even when “ui_right” and “ui_left” is pressed.

I actually cant seem to find the reason for you to reset the velocity at that point.
Try declaring velocity as an empty vector2 at the start of _physics_process then set idle animation to be playing if the player is not moving or damaging stuff.

Thanks I thought that i have done something wrong but was not able to see that. Thanks anyways

Dinoking | 2020-12-01 14:31