Difference between self.position.x+=1 and motion.x = 1 (motion =Vector2())

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

In GD SCRIPT

Ex.1

motion = Vector2()

func _physics_process(delta):
     if Input.is_action_pressed("ui_right"):
           **motion.x = 10**

Ex.2

func _physics_process(delta):
     if Input.is_key_presses(KEY_RIGHT):
            **self.position.x +=10**

In the Above code both will move the position of a sprite to a positive x direction, but what is the mechanism behind moving them, like the difference.

I edited your post for readability. In future, please format your code samples by putting four spaces in front of each line, or using the formatting button in the editor toolbar above.

kidscancode | 2018-09-04 19:02

:bust_in_silhouette: Reply From: kidscancode

Nothing will move in the first example, because all you’re doing is changing a variable called motion that you created yourself. You can use that variable later as a value to move the object.

In the second example, the node will move (if it’s a Node2D) because position is a member property of Node2D-derived objects. Note that you don’t need to explicitly use self when referring to the scripted node’s properties. Also note that depending on the type of node (PhysicsBody2D for example) directly changing the position property is not the correct method to move the object.