0 votes

in Godot3.2,clamp2d(Player) works in standalone scene but doesn't work when instanced in Main scene(both as Child node through Scene ui and as a Packed Scene through Script).
While trying to clamp a kinematic body2d sprite,it is clamped only along positive X&Yaxis and at the right and bottom borders the sprite goes off screen.What's missing?

Main setup-
Player scene
Game Background (Sprite)

Player setup -
KinematicBody2d
ColllisionShape2d-
Sprite

extends KinematicBody2D
var speed = 40
var screen_size 
var sprite_x
var sprite_y 

func _ready():
    screen_size = get_viewport_rect().size
    sprite_x = $Sprite.texture.get_width()/ 2.0 
    sprite_y = $Sprite.texture.get_height() / 2.0  

    print("screen_size.x - sprite_x = ",screen_size.x - sprite_x)
    print("screen_size.y- sprite_y = ",screen_size.y - sprite_y)




func _process(_delta):
    var velocity = Vector2()  # player movement 
    if Input.is_action_pressed("ui_right"):
        velocity.x += 1.0
    if Input.is_action_pressed("ui_left"):
        velocity.x -= 1.0
    if Input.is_action_pressed("ui_down"):
        velocity.y += 1.0
    if Input.is_action_pressed("ui_up"):
        velocity.y -= 1.0
    if velocity.length() > 0:
        velocity = velocity.normalized() * speed 

    position += velocity * _delta

    position.x = clamp(position.x, 0, screen_size.x - sprite_x) 
    position.y = clamp(position.y, 0, screen_size.y - sprite_y)     

    position = move_and_slide(position)
in Engine by (51 points)
edited by

1 Answer

0 votes

position = move_and_slide(position) is wrong

corrected code :

func _process(_delta):
  var velocity = Vector2()  # player movement 
  if Input.is_action_pressed("ui_right"):
      velocity.x += 1.0
  if Input.is_action_pressed("ui_left"):
      velocity.x -= 1.0
  if Input.is_action_pressed("ui_down"):
      velocity.y += 1.0
  if Input.is_action_pressed("ui_up"):
      velocity.y -= 1.0

  velocity = velocity.normalized() * speed 
  move_and_slide(velocity)

  position.x = clamp(position.x, 0, screen_size.x - sprite_x) 
  position.y = clamp(position.y, 0, screen_size.y - sprite_y)     
by (751 points)

This doesn't change anything.Move and slide() returns a positon vector ,which If not stored in var position makes the debugger to "complain".Infact it is better to store moveandslide() in position to stop unnecessary debug complains.

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.