once the player releases the arrow key how to keep the object moving in that direction

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

extends Node2D

const snake_color = Color(0,1,0)

const Dim = Vector2(10,10)

var snake = Vector2()

func _process(delta):
move()
#once player release the arrow key the box should keep moving
update()

func _draw():
draw_rect(Rect2(snake*Dim, Dim), snake_color)

func move():

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 

#Thank You

:bust_in_silhouette: Reply From: ColossalGnome

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.

lincolnpepper | 2018-04-12 20:18