Attention | Topic was automatically imported from the old Question2Answer platform. | |
Asked By | superkp |
I’m new to Godot and I’m trying to follow the tutorial here: https://www.youtube.com/watch?v=FgtekgMca2E
This tutorial is obviously for version 2.0 and I’m coding in 3.1 - my below code is changed in a few ways to reflect that.
I’m running into a problem that I don’t understand as far as getting the code updated, and I’d like to understand what it is - I think that it’s a key to my own understanding of how 3.1 is doing a few things here.
Something is going wrong when I try to run it as-is. I get an error: "Invalid get index ‘width’ (on base: ‘Vector2’)
If I comment out the clamping lines at the end, it runs, but my player is obviously not clamped and can wander off the visible space of the game when run.
This could be the fact that (after checking the documentation for “get_viewport_rect”), “size” is just a vector, and not a rect2, which is what clamp would need if we are calling “screensize.width” there at the end.
OR, I’m not understanding something about how we call ‘get_view_rect().size’, and it’s returning something useful, but either clamp is working in a way that I don’t understand or the “.width” portion is working in a way I don’t understand. And I’d really like to understand this.
SO, this is the script on player.tscn, which also includes a sprite node and a collisionshape2d node. The entire script is below. I’m using “…” to indicate indents. Sorry for any issue with formatting, this is my first post here.
extends Area2D
export var speed = 400
var screensize
var extents
var vel = Vector2()
func _ready():
…set_physics_process(true)
…screensize = get_viewport_rect().size
…extents = get_node(“CollisionShape2D”).get_shape().get_extents()
…set_position(screensize / 2)
func _physics_process(delta):
…var input = Vector2(0, 0)
…input.x = int(Input.is_action_pressed(“ui_right”)) - int(Input.is_action_pressed(“ui_left”))
…input.y = int(Input.is_action_pressed(“ui_down”)) - int(Input.is_action_pressed(“ui_up”))
…vel = input.normalized() * speed
…var pos = get_position() + vel * delta
…position.x = clamp(position.x, 0, screensize.width)
…position.y = clamp(position.y, 0, screensize.height)
…set_position(pos)