I’m building a prototype game and have some multiplayer functionality hooked up. I am running into an issue with sending a float over the wire though. Curious if anyone has run into this, or can tell me what the issue is.
The structure that I send looks like this:
struct TRMessageHeader {
int length;
int code;
};
struct TRMessagePushPeer {
struct TRMessageHeader header;
float force;
};
My code that sends it over the wire looks like this:
- (void) testFloat:(int) floatValue {
struct TRMessagePushPeer message = {0};
message.header.code = TRMessageCodePushPeer;
message.header.length = sizeof(message);
message.force = floatValue;
NSArray * peers = [_session peersWithConnectionState:GKPeerStateConnected];
NSData * data = [NSData dataWithBytes:&message length:sizeof(message)];
NSError * error = NULL;
[_session sendData:data toPeers:peers withDataMode:GKSendDataReliable error:&error];
}
My receiving code looks like this:
- (void) onPeerPushed:(NSNotification *) notification {
NSDictionary * userInfo = [notification userInfo];
NSData * messageData = [userInfo objectForKey:@"messageData"];
struct TRMessagePushPeer * message = (struct TRMessagePushPeer *)[messageData bytes];
NSLog(@"peer sent float :%f",message->force);
}
So the issue I’m having is if i call testFloat:0.4573, then the receiving peer’s float value is 0. If I call testFloat:1.3458 then the receiving peer’s float value is 1.
So it seems like it’s rounding down in the peer receive code but I’m not sure why.
I figure encoding the float with IEEE754 would work, but I would like to know why this doesn’t work as is before I encode it.
- (void) testFloat:(int) floatValue…I think that would be your problem – you’re casting your float as an int in the method declaration. It will be automatically cast to an int when it is passed in. You will probably kick yourself once you see this!
Change it to this:
- (void) testFloat:(float) floatValue