0 votes

On instancing the 2Dplayer script in player scene, the player coordinates match with screen coordinates ,but when instanced as a child node in the main scene, it shows completely different player position coordinates. .Also,tried converting the player postion to global,but the issue still exists.
How to resolve this?

Images can be found here

----------------------------------------------------- Player Script -------------------------------------------

extends Area2D
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()
    sprite_y = $Sprite.texture.get_height() 
    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 = to_global(position)
    position.x = clamp(position.x, 0, screen_size.x - sprite_x) 
    position.y = clamp(position.y, 0, screen_size.y - sprite_y)     
    print("Player position = (",position.x,",",position.y,")")

---------------------------------------------- Main Script --------------------------------------------

extends Node2D
export (PackedScene) var PlayerMain
var screen_size 

func _ready():
    screen_size = get_viewport_rect().size
func _process(_delta):
    var pos = Vector2()
    pos = $Area2D/Sprite.position
    print("Player_main position  = ",pos)
    $playerPos.clear()
    $playerPos.text = str("Player_main position  = (",pos.x," , ",pos.y,")")
    print("screen_size = (",screen_size.x," , ",screen_size.y,")")
    $screenPos.clear()
    $screenPos.text = str("Screen_size = (",screen_size.x," , ",screen_size.y,")")
in Engine by (51 points)
edited by

1 Answer

0 votes

Hi,

The position will be relative to the parent node.

try this: get_parent().add_child(node)

by (2,063 points)
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.