gpt4 book ai didi

ios - 如何通过 GKSession 蓝牙发送整数数组

转载 作者:行者123 更新时间:2023-11-29 11:02:51 27 4
gpt4 key购买 nike

我在通过 GKSession 发送整数数组时遇到问题。

我是这样做的:

发送。

-(void)sendData {
NSMutableArray *myArray = [[NSMutableArray alloc] init];
[myArray addObject:[NSNumber numberWithInteger:snakeHead.position.x]];
[myArray addObject:[NSNumber numberWithInteger:snakeHead.position.y]];
[myArray addObject:[NSNumber numberWithInteger:direction.x]];
[myArray addObject:[NSNumber numberWithInteger:direction.y]];
[myArray addObject:[NSNumber numberWithInteger:bodyOffsetX]];
[myArray addObject:[NSNumber numberWithInteger:bodyOffsetY]];
[myArray addObject:[NSNumber numberWithInteger:amountBodies]];


NSData* encodedArray = [NSKeyedArchiver archivedDataWithRootObject:myArray];

[snakeSession sendData:encodedArray toPeers:snakePeers withDataMode:GKSendDataReliable
error:nil];
[encodedArray release];
}

sendData 函数是从调度程序调用的。

接收它。

-(void)receiveData:(NSData *)data fromPeer:(NSString *)peer inSession:(GKSession *)session
context:(void *)context {
NSArray *hisArray = [NSKeyedUnarchiver unarchiveObjectWithData:data];

snakeHead2.position = ccp([[hisArray objectAtIndex:0] integerValue],
[[hisArray objectAtIndex:1] integerValue]);

direction2 = ccp([[hisArray objectAtIndex:2] integerValue],
[[hisArray objectAtIndex:3] integerValue]);

bodyOffsetX2 = [[hisArray objectAtIndex:4] integerValue];
bodyOffsetY2 = [[hisArray objectAtIndex:5] integerValue];
amountBodies2 = [[hisArray objectAtIndex:6] integerValue];
}

这不起作用,游戏崩溃了。

那么我做错了什么?

最佳答案

这是我会做的。它甚至发送更少的字节! (更快)

// to send
int snakeHead_position_x = 0;
int snakeHead_position_y = 0;
int direction_x = 0;
int direction_y = 0;
int bodyOffsetX = 0;
int bodyOffsetY = 0;
int amountBodies = 0;

NSString *package = [NSString stringWithFormat:@"%i|%i|%i|%i|%i|%i|%i",
snakeHead_position_x, snakeHead_position_y, direction_x,
direction_y, bodyOffsetX, bodyOffsetY, amountBodies];

NSData *data = [package dataUsingEncoding:NSASCIIStringEncoding];
assert(data); // this is critical don't remove!

//printf("sending %u bytes...\n", data.length);

[snakeSession sendData:data toPeers:snakePeers withDataMode:GKSendDataReliable error:nil];


// to retrieve

NSArray *intArray = [[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] componentsSeparatedByString:@"|"];

int snakeHead_position_x = [intArray[0] intValue];
int snakeHead_position_y = [intArray[1] intValue];
int direction_x = [intArray[2] intValue];
int direction_y = [intArray[3] intValue];
int bodyOffsetX = [intArray[4] intValue];
int bodyOffsetY = [intArray[5] intValue];
int amountBodies = [intArray[6] intValue];

关于ios - 如何通过 GKSession 蓝牙发送整数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15056143/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com