Attention | Topic was automatically imported from the old Question2Answer platform. | |
Asked By | starzar |
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)