Can't get variable from player script

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

I’m trying to get the velocity from the player to predict where the player (KinematicBody2D) will be in 0.5 seconds but when printing the predicted position of the player it returns [0,0]. Also, after putting a dot after the player variable it doesn’t suggest velocity which makes me think that it’s because the velocity variable needs to be public in some way?

extends KinematicBody2D

var player : KinematicBody2D
export var seconds_in_future : float = 0.5
onready var marker = $Marker
var future_player_pos : Vector2

func _ready():
	player = get_tree().current_scene.find_node("Player")

func _process(delta):
	future_player_pos = (player.global_position + player.velocity) * future_player_pos
	print(player.velocity)
:bust_in_silhouette: Reply From: Inces

Look at this code, You introduced variable future_player_pos and forgot about it, never calculated anything with it, and than You make it result of multiplication of actual next frame position and itself ! So it is all the time : 0 = (player.position + player.velocity) * 0 :slight_smile:

:bust_in_silhouette: Reply From: Zylann

What is velocity? Is it a variable you created in the player script? If it is always zero it likely means you are not setting it to any value, or it resets to zero just before your other script runs _process due to execution order. It might help to see the code of your player script where you update that variable.

Note: if you do movements and collisions, better use _physics_process.

after putting a dot after the player variable it doesn’t suggest velocity

Don’t assume Godot will always be right in suggesting or not suggesting things. Suggestions cannot be always accurate, sometimes it will fail.

the velocity variable needs to be public in some way?

GDScript does not have a concept of public or private. There is eventually a convention by placing a _ in front of variable names, but it would still be accessible and yours doesn’t have it anyways.


future_player_pos = (player.global_position + player.velocity) * future_player_pos

This code won’t give you the future position of the player. Assuming velocity is in pixels per second, player.global_position + player.velocity will give you where the player will be 1 second later if it keeps going. But multiplying that result with the previous value of the predicted future position makes no sense. Perhaps you meant player.global_position + player.velocity * seconds_in_the_future?