0

I am trying to make left and right movements for mobile, I have made 2 TouchScreenButtons and a CanvasLayer for them. Here is my script:

extends Sprite2D

const speed : int = 5

# Called when the node enters the scene tree for the first time.
func _ready():
    pass # Replace with function body.


# Called every frame. 'delta' is the elapsed time since the previous frame.
func _process(delta):
    if Input.is_action_pressed("game_left"):
        position.x += Vector2.LEFT * speed * delta
    if Input.is_action_pressed("game_right"):
        position.x += Vector2.RIGHT * speed * delta

I was trying to make a right and left movement for a 2d mobile game, but I got the Invalid Operants 'float' and 'Vector2' in operator '+' error.

Theraot
  • 31,890
  • 5
  • 57
  • 86
  • 1
    `Vector2.RIGHT` is still a `Vector2`, but `position.x` is a `float`. Try adding directly to `position`, if it is also a `Vactor2`. – Borisonekenobi Aug 11 '23 at 20:09

1 Answers1

2
position.x += Vector2.LEFT * speed * delta

Here position is a vector and you take its X component which is a float. Then you use Vector2.LEFT to add to it but that is a vector, not a float. As the error says you can’t add vectors to scalars.

Most likely left is a negative value and right positive, so remove Vector2.LEFT and subtract the other parts, and remove Vector2.RIGHT and keep the addition:

position.x -= speed * delta
Sami Kuhmonen
  • 30,146
  • 9
  • 61
  • 74