NewCoder
NewCoder

Reputation: 5

How to make a Node2D move?

I'm trying to make a platform game with godot game engine (version 4.3) but can't seem to figure out how make a Node2D move.

I have a Node2D with a Sprite2D child which has a RigidBody2D child which has a CollisionShape2D.

The code below is for the Node2D.

It is written in gdscript.

I tried to set the nodes position to a vector and repeatedly add a vector to it until it reaches a specific position in which I subtract a vector from and check the position again.

extends Node2D
var vectori = Vector2(300,300)
func _process(_delta: float) -> void:
    $Node2D.position = vectori
    if Node2D.position  > Vector2(500,300):
        vectori = vectori + Vector2(10,0)

It ends up giving me the error:

E 0:00:00:0646 moving_floor.gd:5 @ _process(): Node not found: "Node2D" (relative to "/root/level/Node2D").<C++ Error> Method/function failed. Returning: nullptr<C++ Source> scene/main/node.cpp:1792 @ get_node()<Stack Trace> moving_floor.gd:5 @ _process()

Upvotes: 0

Views: 55

Answers (1)

ttrasn
ttrasn

Reputation: 4851

your code generally is correct, but because you wrote "$Node2D" and your node doesn't have a child with the type of Node2D which doesn't exist, so you only need to remove it. change it to this:

extends Node2D

var vectori = Vector2(300, 300)

func _process(_delta: float) -> void:
    position = vectori
    if position.x > 500:
        vectori = vectori + Vector2(10, 0)

hope it fix your code.

Upvotes: 1

Related Questions