Direction variable after inputs not giving desired result

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By TKT
func _input(event):
		
		if(Input.is_action_pressed("ui_up")):
			if((direction*-1==Vector2(0,-1))):
			 return;
			else:direction=Vector2(0,-1)
			
		elif(Input.is_action_pressed("ui_down")):
			
			if(direction*-1==Vector2(0,1)):
			 return;
			else:direction=Vector2(0,1)
			
		elif(Input.is_action_pressed("ui_left")):
			
			if(direction*-1==Vector2(-1,0)):
			 return;
			else:direction=Vector2(-1,0)
			
		elif(Input.is_action_pressed("ui_right")):
			
			if(direction*-1==Vector2(1,0)):
			 return;
			else:direction=Vector2(1,0)
			
		
		if event is InputEventKey and event.pressed:
			gameStarted=true;

in phyiscs process(delta):

  if gameStarted:
    				
    				checkborders()
    			
    				
    				move_snake()
    				head_collision()

move snake funct:

func move_snake():

	
	previousHeadPos = pix2grid(get_node("head").position)
	
	get_node("head").position += direction*scl

Inputs controlling if previous direction opposite of the current direction. If its true dont change direction. However when i looked at the print of consecutive directions they can become opposite of each other.I checked(print) them at move snake function. If i press Left,top,down fastly it breaks the rule . How will i prevent user to make opposite direction press and ignore them.

		
:bust_in_silhouette: Reply From: Thomas Karcher

Use a current_direction and next_direction variable:

  1. In the _input function, only update the next_direction if it is not opposite to the current_direction.
  2. In the move_snake function, move to next_direction and set current_direction to next_direction afterwards.

Thanks for answering. 1) In the _input function, only update the next_direction if it is not opposite to the current_direction. This one is okay. After implementing

   input.key pressed()
    current_direction=Vector2(0,1)
    if !(current_direction*-1)==next_direction:
    next_direction=current_direction

if i print the next_direction in physics _process():
next_direction=(1,0)
next_direction=(-1,0)

and press random arrow keys ,can i get this printed? because it should prevent it.Buti have this problem.

I think i should also say that i have a timer and every 0.2s lets the code run … This snake move is inside the physics process.However its called ever 0.2s. Now i checked this is the cause it seems.

TKT | 2019-07-08 17:34

Yes: Having game logic both in physics process and a timer is not a good idea for such a simple game. Personally, I’d get rid of the physics process (since there’s no need for a constant update in a game like Snake), but it should also be possible to get rid of the timer instead, allowing for a smoother movement, but requiring more effort to get the turns right.

Thomas Karcher | 2019-07-08 23:16