简体   繁体   English

Android蓝牙游戏,需要跨字节流传输int []

[英]Android bluetooth game, need to transfer int[] across byte stream

Here's the situation: I am making a multiplayer version of pong for android. 情况如下:我正在为Android开发多人版本的Pong。 When my paddle connects with the ball, I want to send the other player the point of impact of the ball (as an x,y coordinate) so that the other player's screen can update to show where the ball is coming from as well as the position of my paddle. 当我的球拍与球连接时,我想向其他球员发送该球的撞击点(以x,y坐标表示),以便其他球员的屏幕可以更新以显示该球的来源以及桨的位置。 The other device will calculate the ball's trajectory and eventually repeat this process. 另一个设备将计算球的轨迹,并最终重复此过程。 Essentially what I want is something that looks like this-- 本质上我想要的是这样的东西-

static final int RESPONSE_CODE = (some #);

int[] return_data = {RESPONSE_CODE, myPaddle.x, myPaddle.y, ballImpactPosition.x, ballImpactPosition.y};

blueToothConnection.write(return_data);

The problem here is that bluetoothConnection.write() relies on java.io.OutputStream and so only supports writing a byte[]. 这里的问题是bluetoothConnection.write()依赖于java.io.OutputStream,因此仅支持写入byte []。

So, is there any way to convert my int[] into a byte[] (and back again later)? 那么,有什么方法可以将我的int []转换为byte [](稍后再返回)? If it helps, my int[] will always contain exactly 5 ints, all always positive. 如果有帮助,我的int []将始终恰好包含5个整数,且始终为正数。 Im not sure what the max values of my ints are because that depends on the device's screen size. 我不确定我的整数的最大值是多少,因为这取决于设备的屏幕尺寸。

In this case, the ByteBuffer is your friend: 在这种情况下,ByteBuffer是您的朋友:

Android API link for ByeBuffer Android API链接的ByeBuffer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM