if Input.is_action_pressed("ui_right"):
snake.x += .1
if Input.is_action_pressed("ui_down"):
snake.y +=.1
if Input.is_action_pressed("ui_up"):
snake.y += -.1
if Input.is_action_pressed("ui_left"):
snake.x += -.1
Instead of directly updating the x & y values, you instead should set a velocity & direction, and calculate position based on that.
Without addressing anything else in the code… Something like this ought to work:
extends Node2D
const velocity = 150
const snake_color = Color(0,1,0)
const Dim = Vector2(10,10)
var snakeDirection = Vector2(0.0, 0.0)
var snakePosition = Vector2(0.0, 0.0)
func _process(delta):
move()
snakePosition = snakeDirection * velocity * delta
func draw():
drawrect(Rect2(snakePosition*Dim, Dim), snake_color)
func move():
if Input.is_action_pressed("ui_right"):
snakeDirection.x = 1
if Input.is_action_pressed("ui_down"):
snakeDirection.y = 1
if Input.is_action_pressed("ui_up"):
snakeDirection.y = -1
if Input.is_action_pressed("ui_left"):
snakeDirection.x = -1
If you don’t want diagonals, set both x and y for each input direction.
Probably you really want a KinematicBody2D here too instead of Node2D…
Actually, velocity used a vector to update position, which implies direction as well as speed. So you should set velocity to a vector representing where you want to go. Speed is how fast you are going and is dimension-neutral, which is what you meant by velocity. But yes, you should use a velocity.