How to set screen width boundaries on the x axis for the player

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

Hello I am a beginer and I don’t know how to set boundaries for a player that moves in the x axis ,left and right, so it won’t get out of the screen. I have tried clamp and clamped but I think I didn’t use them correctly. This is my code for the player:

extends KinematicBody2D
const up=Vector2(0,-1)
const max_speed=200
const acceleration=50
const gravity=10
const Bullet=preload(“res://scenes/bullet.tscn”)
var motion = Vector2()

func _ready():

pass

func _physics_process(delta):

if Input.is_action_pressed("btn_right"):
	$Sprite.flip_h=true
	motion.x=min(motion.x+acceleration,max_speed)
	move_and_slide(motion)

elif Input.is_action_pressed("btn_left"):
	$Sprite.flip_h=false
	motion.x=max(motion.x-acceleration,-max_speed)
	move_and_slide(motion)
else:
	motion.x=lerp(motion.x,0,0.2)

if Input.is_action_just_pressed("btn_fire"):
	var bullet=Bullet.instance()
	var ground=get_parent().get_node("ground")
	get_parent().add_child_below_node(ground,bullet)
	bullet.position = $bullet_spawn.global_position
motion.y += gravity
motion=move_and_slide(motion,up)
pass
:bust_in_silhouette: Reply From: Thewolfs

You can get your viewport’s rectangle with this :

get_viewport().get_visible_rect()

This gives you the coordinates of the top left corner, the size of your viewport and the bottom right corner. Then you would just have to check your position against the top left corner and the bottom corner like this :

#Player position
var position : Vector2

var viewportInfo : Rect2 = get_viewport().get_visible_rect()

if position.x < viewportInfo.position.x:
    position.x = viewportInfo.position.x

if position.y < viewportInfo.position.y:
    position.y = viewportInfo.position.y

if position.x >= viewportInfo.end.x:
    position.x = viewportInfo.end.x-1

if position.y < viewportInfo.end.y:
    position.y = viewportInfo.end.y-1

Change this so that it will match your current code (this is usually not how you set a node’s position I’ve just simplified it for the purpose of this example)

Thank you very much for the help.

DudeGames | 2019-06-23 11:33