How to make the movement in one direction while sprite is moving

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

I want to know what I must adjust in order for the movement to be in one direction, and the player’s path cannot be changed until he hits the wall

extends KinematicBody2D

const SPEED = 50
var velocity = Vector2()
var swipe = ''
const SWIPED_SPEED = 10
var gameLoop = true

func _process(delta):
		if gameLoop:
			if swipe && swipe != 'swiped':
				if swipe == 'up':
					velocity.y = int(-SPEED*ACCELERATION)
				if swipe == 'down':
					velocity.y = int(SPEED*ACCELERATION)
				if swipe == 'right':
					velocity.x = int(-SPEED*ACCELERATION)
				if swipe == 'left':
					velocity.x = int(SPEED*ACCELERATION)
				swipe = 'swiped'

		velocity = move_and_slide(velocity)
func _input(event):
	if event is InputEventScreenDrag:
		if !swipe:
			if event.relative.y < -SWIPED_SPEED:
				swipe = 'up'
			if event.relative.x < -SWIPED_SPEED:
				swipe = 'right'
			if event.relative.x > SWIPED_SPEED:
				swipe = 'left'
			if event.relative.y > SWIPED_SPEED:
				swipe = 'down'
	elif event is InputEventScreenTouch:
		if !event.pressed:
			swipe = ''
:bust_in_silhouette: Reply From: Wakatta

In your direction checks change if to elif after your first if statement

Assuming you’ve setup walls for detection use KinematicBody2D’s is_on_wall()

func _process(delta):
    if gameLoop:
        if swipe && swipe != 'swiped' && is_on_wall():
            if swipe == 'up':
            elif swipe == 'down':

I have changed if to elif it did not work. The player can still be diverted from its path while moving. As for the walls, I used TileMap and the player stopped when hitting it.

raed | 2021-01-18 20:09

I solved it by adding this code to process func and it work perfect

if velocity.length() == 0:

raed | 2021-01-18 20:09