Search code examples
objective-cswiftcollisionsphero-apisphero

Can't use Sphero collision detection with Swift?


I'm new to Swift and Sphero development but I've been asked to do a game based on collisions with the Sphero. I've managed to implement the driving part without problems so far, but I'm having problems with collisions. I've been looking for code examples and similar issues all over the Internet but everything I've found is based in other languages like JAVA or ObjectiveC.

The code provided by Sphero's official page is the following:

**Enable collision detection**

robot.enableCollisions(true)
robot.sendCommand(RKConfigureCollisionDetectionCommand(forMethod: .Method3, xThreshold: 50, xSpeedThreshold: 30, yThreshold: 200, ySpeedThreshold: 0, postTimeDeadZone: 0.2))

**Handle Async Messages on collision**

func handleAsyncMessage(message: RKAsyncMessage!, forRobot robot: RKRobotBase!) {
    if let collisionMessage = message as? RKCollisionDetectedAsyncData {
    // handleCollisionDetected
    }
}  

I've tried this in many ways, but when executed it won't send any command or even access the handleAsyncMessage method, so I'm starting to think this code is not implemented for Swift. These doubts were intensified when I found that the collision streaming method was implemented somewhere in the official page for ObjectiveC, but for Swift I could only find //Coming Soon!.

Collisions
  [_robot sendCommand:[[RKConfigureCollisionDetectionCommand alloc]
   initForMethod:RKCollisionDetectionMethod3
   xThreshold:50 xSpeedThreshold:30 yThreshold:200 ySpeedThreshold:0 postTimeDeadZone:.2]];

  ...
- (void)handleAsyncMessage:(RKAsyncMessage *)message forRobot:(id<RKRobotBase>)robot {
   if( [message isKindOfClass:[RKCollisionDetectedAsyncData class]]) {

  RKCollisionDetectedAsyncData *collisionAsyncData = (RKCollisionDetectedAsyncData *) message;

    float impactAccelX = [collisionAsyncData impactAcceleration].x;
    float impactAccelY = [collisionAsyncData impactAcceleration].y;
    float impactAccelZ = [collisionAsyncData impactAcceleration].z;

    float impactAxisX = [collisionAsyncData impactAxis].x;
    float impactAxisY = [collisionAsyncData impactAxis].y;

    float impactPowerX = [collisionAsyncData impactPower].x;
    float impactPowerY = [collisionAsyncData impactPower].y;

    float impactSpeed = [collisionAsyncData impactSpeed];
}
}

Should I change the language to ObjectiveC or do you guys know any way to implement this using Swift? Thank you in advance.


Solution

  • This SDK is written in Objective-C; Swift works through Objective-C interoperability built into Swift. Everything should work regardless of the language you choose. It looks like you might be missing the response observer. On the robot you call robot.addResponseObserver(self) making sure you implement the RKResponseObserver protocol.