Move sprite in GDS

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

Hy, I try to move a Sprite in GDS, but it always output error, i’m new in Python & Godot sorry ;3

extends KinematicBody2D

const MOTION_SPEED = 160

func _physics_process(delta):
var motion = Vector2()

if Input.is_action_pressed("move_up"):
	motion += Vector2(0, -1)
if Input.is_action_pressed("move_bottom"):
	motion += Vector2(0, 1)
if Input.is_action_pressed("move_left"):
	motion += Vector2(-1, 0)
if Input.is_action_pressed("move_right"):
	motion += Vector2(1, 0)

motion = motion.normalized() * MOTION_SPEED

What is the error message?

kidscancode | 2018-04-07 23:16

Hi kidscancode, there is no error message, the code just didn’t execute.

Thanks for help.

I’ve try so many way for it… but no way to make it work ;'(

extends KinematicBody2D

var vel = Vector2(1,1)
var sprite

func _ready():
sprite = get_node(“Sprite”)

func _physics_process(delta):
if Input.is_action_pressed(“ui_down”):
sprite.get_viewport_transform().x = sprite.get_viewport_transform().x + vel

Oxiduc | 2018-04-08 08:04

:bust_in_silhouette: Reply From: Oxiduc

Hey, I found the solution ;

extends KinematicBody2D

var vel = Vector2(1,1)
var sprite

func _ready():
    sprite = get_node("Sprite")

func _physics_process(delta):
	if Input.is_action_pressed("ui_down"):
        position.y = position.y + 1
        position.x = 100
        sprite.position = sprite.position + vel

This code works for moving sprite in the scene.

Have a nice day

This won’t work correctly. KinematicBody2D must be moved with move_and_collide() or move_and_slide() or it will not detect collisions.

There are also some large problems with this code.

In your code, you’re changing the position twice - adding 1 to position.y and then locking position.x to 100 for the KinematicBody2D. Then you’re moving the child sprite by (1,1). This seems crazy. Your kinematic body is going to slowly move straight down and your child sprite diagonally, slowly getting farther and farther apart.

You seem to lack some understanding of the way Godot nodes work. I highly recommend reading the docs and trying the tutorial:

It demonstrates a lot of the things you need to know.

kidscancode | 2018-04-08 14:45