how to make player node(kinematicbody2d) stop from go outside viewport/screen?

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

how to make player node(kinematicbody2d) stop from go outside viewport/screen?

func _input(event: InputEvent) -> void:
	global_position = lerp((get_viewport().get_mouse_position()),global_position,0.6)
	if global_position >= get_viewport_rect().size:
         ???????

and why when outside viewport/screen i get this error picture link
enter image description here

this full player codepicture link
enter image description here

enemy code
enter image description here

:bust_in_silhouette: Reply From: njamster
func _input(event: InputEvent) -> void:
	var pos = lerp((get_viewport().get_mouse_position()), global_position, 0.6)
	pos.x = clamp(pos.x, 0, get_viewport_rect().size.x)
	pos.y = clamp(pos.y, 0, get_viewport_rect().size.y)
	global_position = pos

thanks you, can i know why i still get error? i put video in youtube

potatobanana | 2020-03-07 13:27

First of all, judging from both the video and the screenshots you provided (after I wrote my answer), you didn’t apply my code but instead did this:

func _input(event: InputEvent) -> void:
    global_position = lerp((get_viewport().get_mouse_position()),global_position,0.6)
    move_and_slide(global_position, Vector2(0, 0))

So this error has nothing to do with my answer. Nor does it have anything to do with leaving the viewport. The error complains about collider being a null instance, so my guess would be you freed the colliding instance somewhere else in your code.

By the way: the code you’re using in your _input-function moves the player twice. First by setting it’s global_position-property, then by using the move_and_slide function (which expects a velocity vector, not a position vector).

njamster | 2020-03-07 14:32

thank you, yes your code has nothing to do with my error, at first i thought leaving viewport the problem. but i still get the problem even i did’t leave viewport.
so i stop use mouse for movement and use this input

var right = Input.is_action_pressed("ui_right")
var left = Input.is_action_pressed("ui_left")
var up = Input.is_action_pressed("ui_up")
var down = Input.is_action_pressed("ui_down")


movement.x = int(right) - int(left)
movement.y = int(down) - int(up)

var motion = movement.normalized()*move_speed  #need * delta for move_and_collide
move_and_slide(motion,Vector2.ZERO)

i did’t get the problem anymore .

potatobanana | 2020-03-07 16:23

:bust_in_silhouette: Reply From: qq715152910

Camera contains the above functions,
you should take a good look at the API

limit
(top left right bottom)

No need to write in code to achieve this