Hello! I am trying to make a game controlled by a custom controller. For this, I use an arduino to give input to a python script which gives the data to a godot script using UDP. With a lot of help I have scrambled together a script that accomplishes that, but I would like to be able to send data from godot to python and then to the arduino too (for example the player's character died, so the player can't shoot until they respawn). Whatever I tried didn't work, so here is the scripts so far, in case anyone can help me.
gdscript:
extends Node
# Configure the UDP socket for receiving data from Python
var python_address : String = "127.0.0.1"
var python_port : int = 12345
var python_socket := PacketPeerUDP.new()
var data_list
var begin = false
func _ready():
# Bind the socket to the specified address and port
python_socket.bind(python_port, python_address)
func _process(delta):
# Check for incoming data
if python_socket.get_available_packet_count() > 0:
# Receive data from Python
#var data : PacketPeerUDP = python_socket.get_packet()
var data = python_socket.get_packet()
print(data)
# Process the received data as needed
var decoded_data : String = data.get_string_from_utf8()
data_list = decoded_data.split(",")
#print(data_list)
begin = true
python:
import serial
from serial import Serial
from pynput.mouse import Button, Controller
from socket import socket, AF_INET, SOCK_DGRAM
m_left = False
m_right = False
godot_address = ('127.0.0.1', 12345) # Adjust the IP and port as needed
godot_socket = socket(AF_INET, SOCK_DGRAM)
try:
# Setting Serial port number and baudrate
ser = serial.Serial('COM4', 9600)
except:
print("Mouse not found or disconnected.")
k=input("Press any key to exit.")
mouse = Controller()
while True:
try:
dump = ser.readline() # Reading Serial port
dump = str(dump) # Converting byte data into string
dump = dump[2:-5] # Cleaning up the raw data recieved from serial port
data = dump.split(',') # Spliting up the data to individual items in a list. the first item being the data identifier
print(data)
data_bytes = ','.join(data).encode('utf-8')
godot_socket.sendto(data_bytes, godot_address)
except (ValueError, IndexError):
pass
P.S.: I know there are better ways to do this (with gdnative for example), but this is the simplest one. I use godot 4.1