Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm using this code to send information to Pure Data, in the Python console I see the two different variables, however Pure Data keeps receiving them added together not as two separate numbers.

import bge

# run main program
main()

import socket

# get controller 
cont2 = bge.logic.getCurrentController()
# get object that controller is attached to 
owner2 = cont2.owner
# get the current scene 
scene = bge.logic.getCurrentScene()
# get a list of the objects in the scene 
objList = scene.objects

# get object named Box 
enemy = objList["enemy"]
enemy2 = objList["enemy2"]

# get the distance between them 
distance = owner2.getDistanceTo(enemy)
XValue = distance  
print (distance)
# get the distance between them 
distance2 = owner2.getDistanceTo(enemy2)
XValue = distance2  
print (distance2)    

tsr = str(distance + distance2)     
tsr += ';'
host = '127.0.0.1'
port = 50007
msg = '123456;'

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.send(tsr.encode())
s.shutdown(0)
s.close()

I need to send up to 10 different distances from objects, this is to do with finding distances from enemies

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
174 views
Welcome To Ask or Share your Answers For Others

1 Answer

The problem is entirely in your python code:

You have two variables distance1 and distance2 (let's assume that distance1=666 and distance2=42 and then you construct a string:

tsr = str(distance1 + distance2)

Now this will first evaluate the expression distance1+distance2 (summing them up to 708) and then create a string from that value ("708"). So your Python script sends the munged data.

So your first step is to convert your values to strings before "adding" them (since adding strings is really appending them):

tsr = str(distance1) + str(distance2)

But this will really give you a string "66642", as you haven't told the appender to separate the to values with a whitespace.

So one correct solution is:

tsr = str(distance1) + " " + str(distance2)
tsr += ";"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...