Please help me. As we know in the snake game, if we are currently moving to the right: we cannot move to the left, we have to move either up or down or persist with moving right. And so on respectively for the other directions. So I came up with the following code:
extends Area2D
export var SPEED=100
var input_vector= Vector2.ZERO
var canMove = {'left':false, 'right':false, 'up':false, 'down':false}
var moving = {'left':false, 'right':false, 'up':false, 'down':false}
func _physics_process(delta):
position += input_vector*SPEED*delta
if Input.is_action_just_pressed("ui_right"):
input_vector.x=1
input_vector.y=0
if Input.is_action_just_pressed("ui_left"):
input_vector.x=-1
input_vector.y=0
if Input.is_action_just_pressed("ui_up"):
input_vector.x=0
input_vector.y=-1
if Input.is_action_just_pressed("ui_down"):
input_vector.x=0
input_vector.y=1
if input_vector.x<0:
moving['left']=true
if input_vector.x>0:
moving['right']=true
if input_vector.y<0:
moving['up']=true
if input_vector.y>0:
moving['down']=true
if moving['left']==true:
canMove['right']=false
canMove['up']=true
canMove['down']=true
if moving['right']==true:
canMove['left']=false
canMove['up']=true
canMove['down']=true
if moving['up']==true:
canMove['right']=true
canMove['left']=true
canMove['down']=false
if moving['down']==true:
canMove['right']=true
canMove['left']=true
canMove['up']=false
if canMove['left']==false:
input_vector.x= abs(input_vector.x)
if canMove['right']==false:
input_vector.x= -abs(input_vector.x)
if canMove['up']==false:
input_vector.y= abs(input_vector.y)
if canMove['down']==false:
input_vector.y= -abs(input_vector.y)