User's name not showing in multiplayer godot waiting room - game-development

so i was following a multiplayer godot tutorial on YouTube by ruyuse everything worked well (the server) until i got to the waiting room which is supposed to show the names of players joined, from this to this but when i try mine the lobby is the same but the waiting room ends up like this i know there is something of but its my first time making a multiplayer game so pls help.
This is my server side:
server.gd
func _ready():
start_server()
func start_server():
network.create_server(port, max_players)
get_tree().set_network_peer(network)
network.connect("peer_connected", self, "_player_connected")
network.connect("peer_disconnected", self, "_player_disconnected")
print("server started")
func _player_connected(player_id):
print("Player: " + str(player_id) + " Connected")
func _player_disconnected(player_id):
print("Player: " + str(player_id) + " Disconnected")
remote func send_player_info(id, player_data):
players[id] = player_data
rset("players", players)
rpc("update_waiting_room")
The client:
server.gd:
extends Node
const DEFAULT_IP = "127.0.0.1"
const DEFAULT_PORT = 3234
var network = NetworkedMultiplayerENet.new()
var selected_IP
var selected_port
var local_player_id = 0
sync var players = {}
sync var player_data = {}
func ready():
get_tree().connect("network_peer_connected", self,"_player_connected")
get_tree().connect("network_peer_disconnected", self,"_player_disconnected")
get_tree().connect("connection_failed", self,"_connected_fail")
get_tree().connect("server_disconnected", self,"_server_disconnected")
func _connect_to_server():
get_tree().connect("connected_to_server", self, "_connected_ok")
network.create_client(selected_IP, selected_port)
get_tree().set_network_peer(network)
func _player_connected(id):
print("player: " + str(id) + "Connected")
func _player_disconnected(id):
print("player: " + str(id) + "Disconnected")
func _connected_ok():
print("successfully connected to server")
register_player()
rpc_id(1, "send_player_info", local_player_id, player_data)
func _connected_fail():
print("failed to connect")
func _server_disconnected():
print("server disconnected")
func register_player():
local_player_id = get_tree().get_network_unique_id()
player_data = Save.save_data
players[local_player_id] = player_data
sync func update_waiting_room():
get_tree().call_group("WaitingRoom", "refresh_players", players)
lobby.gd:
extends Control
onready var player_name = $CenterContainer/VBoxContainer/GridContainer/NameTextBox
onready var selected_IP = $CenterContainer/VBoxContainer/GridContainer/IPTextBox
onready var selected_port = $CenterContainer/VBoxContainer/GridContainer/PortTextBox
onready var waiting_room = $WaitingRoom
onready var ready_btn = $WaitingRoom/CenterContainer/VBoxContainer/ReadyButton
func _ready():
player_name.text = Save.save_data["Player_name"]
selected_IP.text = (Server.DEFAULT_IP)
selected_port.text = str(Server.DEFAULT_PORT)
func _on_Join_button_pressed():
Server.selected_IP = selected_IP.text
Server.selected_port = int(selected_port.text)
Server._connect_to_server()
show_waiting_room()
func _on_NameTextBox_text_changed(new_text):
Save.save_data["Player_name"] = player_name.text
Save.save_game()
func show_waiting_room():
waiting_room.popup_centered()
func _on_ReadyButton_pressed():
ready_btn.disabled = true
waiting_room.gd:
extends Popup
onready var player_list = $CenterContainer/VBoxContainer/ItemList
func _ready():
player_list.clear()
func refresh_players(players):
player_list.clear()
for player_id in players:
var player = players[player_id]["Player_name"]
player_list.add_item(player, null, false)
save.gd:
var save_data = {}
func _ready():
save_data = get_data()
func get_data():
var file = File.new()
if not file.file_exists(SAVEGAME):
save_data = {"Player_name": "Unnamed"}
save_game()
file.open(SAVEGAME, File.READ)
var content = file.get_as_text()
var data = parse_json(content)
save_data = data
file.close()
return(data)
func save_game():
var save_game = File.new()
save_game.open(SAVEGAME, File.WRITE)
save_game.store_line(to_json(save_data))
and these are the errors i get on the server side (i realy don"t know what they mean)
I really hope this is not to long of a question because i really need help.
Thank you for reading.
sorry for the typos

Related

I tried to run this code and every time I run it shows this result

private fun moveMarkerAnimation(key: String, newData: AnimationModel, marker: Marker?, from: String, to: String) {
if (!newData.isRun)
{
compositeDisposable.add(
iGoogleAPI.getDirections(
"driving",
"less_driving",
from, to,
getString(R.string.google_api_key1)
)!!.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { returnResult ->
Log.d("API_RETURN",returnResult,)
try {
val jsonObject = JSONObject(returnResult)
val jsonArray = jsonObject.getJSONArray("routes")
for ( i in 0 until jsonArray.length())
{
val route = jsonArray.getJSONObject(i)
val poly = route.getJSONObject("overview_polyLine")
val polyLine = poly.getString("points")
polylineList = Common.decodePoly(polyLine) as java.util.ArrayList<LatLng?>
}
handler = Handler()
index = -1
next = 1
val runnable = object :Runnable{
override fun run() {
if (polylineList!!.size > 1)
{
if (index< polylineList!!.size)
{
index ++
next = index+1
start = polylineList!![index] !!
end = polylineList!![next]!!
}
val valueAnimator = ValueAnimator.ofInt(0,1)
valueAnimator.duration = 3000
valueAnimator.interpolator = LinearInterpolator()
valueAnimator.addUpdateListener { value ->
v = value.animatedFraction
lat = v*end !!.latitude + (1-v) * start!!.latitude
lng = v*end !!.longitude+ (1-v) * start!!.longitude
val newPos = LatLng(lat,lng)
marker!!.position = newPos
marker!!.setAnchor(0.5f,0.5f)
marker!!.rotation = Common.getBearing(start!!,newPos)
}
valueAnimator.start()
if (index < polylineList!!.size-2)
{
handler!!.postDelayed(this,1500)
}else if (index < polylineList!!.size-1)
{
newData.isRun = false
Common.driversSubscrib.put(key,newData)
}
}
}
}
handler!!.postDelayed(runnable,1500)
}
catch (e:java.lang.Exception){
Snackbar.make(requireView(),e.message!!,Snackbar.LENGTH_LONG).show()
}
When the site changes from from firebase this result appears
022-04-26 13:19:30.912 23482-23482/com.example.bustrackerriderapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.bustrackerriderapp, PID: 23482
io.reactivex.exceptions.OnErrorNotImplementedException: The exception was not handled due to missing onError handler in the subscribe() method call. Further reading
what should I do to fix this problem

Koltin : ACTION_BOND_STATE_CHANGED not returning BluetoothDevice.BOND_BONDED

So I have a device where I need to put in a pin code, this all works however I can't detect when the bond has completed, only when bonding has started.
Android 10
if (action == BluetoothDevice.ACTION_BOND_STATE_CHANGED) {
val state = intent.extras?.get(BluetoothDevice.EXTRA_BOND_STATE) as Int
val device = getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
val previousBondState = getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, -1)
val bondState = getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1)
val bondTransition = "${previousBondState.toBondStateDescription()} to " +
bondState.toBondStateDescription()
Timber.w("${device?.address} bond state changed | $bondTransition ${state.toBondStateDescription()}")
}
fun listenToBondStateChanges(context: Context) {
context.applicationContext.registerReceiver(
viewModel.btConnectionManager.broadcastReceiver,
IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED)
)
}

How to force the notification to use the Alarmsound and not the Ringtone?

My Problem: i have set the notification as an alarm.When the sound on the cellphone is on, the cellphone takes the sound as an alarmsound. But if the cellphone is muted, the cellphone vibrates, but there is no sound./no alarmsound/no ringtone. I cant even see the volume/sound level for the alarm, only the volume of the ringtone is visible on the cellphone.The alarm works fine on different emulator-> So the question is: Is there a way to force the notification to use the Alarmsound and not the Ringtone? An idea would be appreciated.(PS: i have tried it also as a service with notification)Thank you!here is my my code:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channelImportance = if (playSound) {
NotificationManager.IMPORTANCE_HIGH
} else {
NotificationManager.IMPORTANCE_LOW
}
val audioAttribute = AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ALARM)
.build()
val notificationSound: Uri =
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM)
val notyChannel =
NotificationChannel(channelID, channelName, channelImportance)
notyChannel.enableLights(true)
notyChannel.lightColor = Color.RED
notyChannel.setSound(notificationSound,audioAttribute)
notyChannel.enableVibration(true)
notyChannel.vibrationPattern = longArrayOf(
1000,100,100,100,1000,100,100,100,1000)
this.createNotificationChannel(notyChannel)
this works:
val audio =
context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
if (mode == 0) audio.ringerMode =
AudioManager.RINGER_MODE_SILENT else if (mode == 1) audio.ringerMode =
AudioManager.RINGER_MODE_VIBRATE else if (mode == 2) audio.ringerMode =
AudioManager.RINGER_MODE_NORMAL

Using SoundPool for games

class SoundPlayer(context: Context) {
// For sound FX
private val soundPool: SoundPool = SoundPool(10, // Here
AudioManager.STREAM_MUSIC,
0)
companion object {
var playerExplodeID = -1
var invaderExplodeID = -1
var shootID = -1
var damageShelterID = -1
var uhID = -1
var ohID = -1
}
init {
try {
// Create objects of the 2 required classes
val assetManager = context.assets
var descriptor: AssetFileDescriptor
// Load our fx in memory ready for use
descriptor = assetManager.openFd("shoot.ogg")
shootID = soundPool.load(descriptor, 0)
descriptor = assetManager.openFd("invaderexplode.ogg")
invaderExplodeID = soundPool.load(descriptor, 0)
descriptor = assetManager.openFd("damageshelter.ogg")
damageShelterID = soundPool.load(descriptor, 0)
descriptor = assetManager.openFd("playerexplode.ogg")
playerExplodeID = soundPool.load(descriptor, 0)
descriptor = assetManager.openFd("damageshelter.ogg")
damageShelterID = soundPool.load(descriptor, 0)
descriptor = assetManager.openFd("uh.ogg")
uhID = soundPool.load(descriptor, 0)
descriptor = assetManager.openFd("oh.ogg")
ohID = soundPool.load(descriptor, 0)
} catch (e: IOException) {
// Print an error message to the console
Log.e("error", "failed to load sound files")
}
}
fun playSound(id: Int){
soundPool.play(id, 1f, 1f, 0, 0, 1f)
}
}
i have a problem with SoundPool cant use it is says constructor SoundPool is deprecated
i'm kinda new so don't know how to fix this (watched many videos and searched everywhere but i cant fix it)
so maybe someone can help me out tell me what to do
When something is deprecated, there always should be a hint what to use instead.
So you need to use SoundPool.Builder to create new instance of an object.
But there is one issue if you target API level that was release before SoundPool.Builder then you will get ClassNotFoundException.
So general approach is to check the API level and do things in old way before API X(when new feature was introduced), and a new way after API X:
#Suppress("DEPRECATION")
fun buildSoundPool(maxStreams: Int):SoundPool =
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val attrs = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_GAME)
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.build()
SoundPool.Builder()
.setAudioAttributes(attrs)
.setMaxStreams(maxStreams)
.build()
} else {
SoundPool(maxStreams, AudioManager.STREAM_MUSIC, 0)
}
Then:
private val soundPool: SoundPool = buildSoundPool(10)
Also I do recommend to use my custom implementation of SoundPool because lots of platform dependent issues that was introduced in original SoundPool on different versions on Android.

Playing WAV data with AVAudioEngine

Currently, I'm getting an EXC_BAD_ACCESS error on the audio thread, and I'm trying to deduce what is going wrong.
When converting .wav file data from Data to an AVAudioPCMBuffer, do I need to strip the RIFF header first?
import AVFoundation
public class Player : NSObject {
let engine = AVAudioEngine()
public override init() {
super.init()
do {
let _ = engine.mainMixerNode
try engine.start()
} catch {
print("Player error: \(error)")
}
}
#objc public func play(_ data: Data) {
let format = AVAudioFormat(commonFormat: .pcmFormatInt16, sampleRate: 48000, channels: 2, interleaved: true)!
let buffer = data.toPCMBuffer(format: format)!
let player = AVAudioPlayerNode()
engine.attach(player)
engine.connect(player, to: engine.mainMixerNode, format: nil)
player.scheduleBuffer(buffer, at: nil, completionCallbackType: .dataPlayedBack) {
callbackType in
// Nothing in here.
}
player.play()
}
}
Here's the toPCMBuffer extension:
// Taken from: https://stackoverflow.com/a/52731480/2228559
extension Data {
func toPCMBuffer(format: AVAudioFormat) -> AVAudioPCMBuffer? {
let streamDesc = format.streamDescription.pointee
let frameCapacity = UInt32(count) / streamDesc.mBytesPerFrame
guard let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: frameCapacity) else { return nil }
buffer.frameLength = buffer.frameCapacity
let audioBuffer = buffer.audioBufferList.pointee.mBuffers
withUnsafeBytes { addr in
audioBuffer.mData?.copyMemory(from: addr, byteCount: Int(audioBuffer.mDataByteSize))
}
return buffer
}
}
Note: I cannot use AVAudioFile because the .wav file data is loaded over-the-wire.
IDK, but my mac crashes if I play interleaved AVAudioPCMBuffers, and garbled audio if they're not float data, so you could convert to non-interleaved float data:
#objc public func play(_ data: Data) {
let sampleRate: Double = 48000
let interleavedFormat = AVAudioFormat(commonFormat: .pcmFormatInt16, sampleRate: sampleRate, channels: 2, interleaved: true)!
let interleavedBuffer = data.toPCMBuffer(format: interleavedFormat)!
let nonInterleavedFormat = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: sampleRate, channels: 2, interleaved: false)!
let nonInterleavedBuffer = AVAudioPCMBuffer(pcmFormat: nonInterleavedFormat, frameCapacity: interleavedBuffer.frameCapacity)!
nonInterleavedBuffer.frameLength = interleavedBuffer.frameLength
let converter = AVAudioConverter(from: interleavedFormat, to: nonInterleavedFormat)!
try! converter.convert(to: nonInterleavedBuffer, from: interleavedBuffer)
let player = AVAudioPlayerNode()
engine.attach(player)
engine.connect(player, to: engine.mainMixerNode, format: nil)
player.scheduleBuffer(nonInterleavedBuffer, at: nil, completionCallbackType: .dataPlayedBack) {
callbackType in
// Nothing in here.
}
player.play()
}
extension Data {
func toPCMBuffer(format: AVAudioFormat) -> AVAudioPCMBuffer? {
assert(format.isInterleaved)
let streamDesc = format.streamDescription.pointee
let frameCapacity = UInt32(count) / streamDesc.mBytesPerFrame
guard let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: frameCapacity) else { return nil }
buffer.frameLength = buffer.frameCapacity
let b = UnsafeMutableBufferPointer(start: buffer.int16ChannelData![0], count: buffer.stride * Int(frameCapacity))
let bytesCopied = self.copyBytes(to: b)
assert(bytesCopied == count)
return buffer
}
}