Some Physics functions in AndEngine GLES1.0 + Box2D

AndEngine is one of the best game engines available to build 2D games on the Android platform. It has a load of great features, one of which its integration with the Box2D physics engine. This is done via a great extension.

There are many sources out there to help developers with integrating physics features in to AndEngine, including examples from the author of the engine himself, however, I thought of writing my own helpful guide with some of the lesser-explained functions of AndEngine’s physics engine.

You’ll be able to use this awesome blog post by Maya PoschΒ to set up AndEngine and get it configured with the AndEngine Physics Box2D Extension. It’s a bit complicated, so if you’re lazy like me you could find the compiled sources from the previously-linked Examples repository (though this is NOT recommended).

Now, to get started on some of the functions that you’ll need. The Box2D environment, when oversimplified, contains the following main elements:

  • Physics World: This is where all the exciting business goes on, and where all the elements related to physics are stored and manipulated. Welcome to the world of physics!
  • Bodies: Bodies are similar to sprites in any game; they’re what move about, crash in to each other etc.
  • Vectors: These are what you’ll be applying on your bodies (you do know your basic physics, right?) to make them move around, rotate, stop, and every other conceivable thing.

Basics aside, we’ll look at a few functionalities that are rarely explained in most AndEngine physics examples:

  1. Contact Listeners:

Contact listeners are Box2D’s equivalent to collision detection in game engines. A ContactListener is defined for the Physics World in general, and will handle all contacts that happens in that world. That means, when a contact listener fires, you’ll only get the Fixtures (and underlying Bodies) of that particular contact to manipulate. Handling contact listeners in this way can get pretty dirty pretty fast, it turns in to a mess of checking fixtures for their underlying attributes and rechecking to see if they’re the actual body within the physics world that you want to check for collisions. Well, you did want to have smooth physics in your game, right? Now pay the price. πŸ˜‰

Following is a code snippet from a car racing game I worked on:

mPhysicsWorld.setContactListener(new ContactListener() {

			public void preSolve(Contact contact, Manifold oldManifold) {

			}

			public void postSolve(Contact contact, ContactImpulse impulse) {

			}

			public void endContact(Contact contact) {

			}

			public void beginContact(Contact contact) {

				if ( contact.getFixtureA().getBody().getUserData() != null &&
						contact.getFixtureB().getBody().getUserData() != null  ) {
                                        //I stored a 'Car' object in the userdata of each physics body as I created it
					final Car carA = (Car)contact.getFixtureA().getBody().getUserData();
					final Car carB = (Car)contact.getFixtureB().getBody().getUserData();
					if ( carA.getId() == 1 || carB.getId() == 1 ) {
						carState = CAR_STATE_CRASHED;
						vibrator.vibrate(100);
                                        }
                                }
                      }
});

By returning the bodies associated with each fixture in teh contact, I have managed to get the ‘Car’ type objects stored within the userdata elements within each body. By checking a specific value within these car objects, I have decided what to do next. Any contact handling that you’d do with AndEngine + Box2D would have to be a lot of if-else clauses where you check whether the bodies crashing together within the physics world are the bodies you want to check for collisions with. The presolve() an postsolve() methods are concerned with preparing the physics world for the contact, where you can set various attributes like whether contacts are enabled at that point.

2. Setting your body’s velocity to 0:

This might seem like a weird requirement, but believe me, after your sprites start bouncing around the screen like crazy ping pong balls, you’ll thank me. This is something it took me a while to figure out, so I thought I’d share:

Vector2 linearZero = Vector2Pool.obtain(0,0);
playerBody.setLinearVelocity(linearZero);
Vector2Pool.recycle(linearZero);//don't forget to recycle your vectors! It helps save the environment.

Ok, so you have your playerBody right? What you do is, you initialize a vector with 0 values, and you apply that as the linear velocity to your body. That will stop the body from moving on all plains.

3. Insta-move your sprite to any place on the screen:

Sometimes, even when you have a physics engine at your disposal, you just want to magically materialize your sprite somewhere on the screen. The problem is, if you use the normal AndEngine sprite.setPosition() method, the physics body you’ve attached to the sprite is not going to move with it. You need to use Box2D itself to insta-move your sprite (once you move the body, the sprite will always move with it, but not vice-versa):

 

Vector2 transformVector = Vector2Pool.obtain(newXPosition, newYPosition);
playerBody.setTransform(transformVector, playerBody.getAngle());
Vector2Pool.recycle(transformVector);

Vectors again. Simply build a new vector containing the X and Y coordinates you want to move your sprite to, and use the setTransform() method on the body attached to the sprite.

 

That’s it from me for now. More soon!

Handling HTTP Digest Authentication using Ruby

You may have encountered an authentication-required header when making HTTP requests to various web services or websites. While the basic authentication scheme for HTTP simply requires you to submit username and password details for that particular URL, there are other protocols which enhance the level of security that can be applied to an HTTP connection. HTTP Digest Authentication, which has been specified by this RFC, is one such method than can be used to provide enhanced security for HTTP-based web service connections.

HTTP Digest Authentication is based primarily on two concepts; MD5 hashing and dynamically-generated nonce values. The nonce values are used to ensure that a particular call to the server is part of an ongoing conversation between that particular client and the server, without anyone else (hackers πŸ˜‰ ) butting in.

To call a web service employing HTTP Digest authentication, you must first send an empty request to the server which will return a server-generated nonce value for you. Then you can proceed to the next steps in authentication, which involves hashing your username and password with the nonce in the middle, as well as setting various header values.

Recently, I implemented some Ruby code to call a web service using HTTP Digest authentication, and I thought of sharing my code. I based most of it on the HTTP Digest Auth Ruby Gem.

Here’s the code:

# Build header authorization block to send to given URI
    def build_header_auth(uri, version, httpmethod) response = get_auth_response(uri)
	    @cnonce = Digest::MD5.hexdigest("%x" % (Time.now.to_i + rand(65535)))
        @@nonce_count += 1 response['www-authenticate'] =~ /^(\w+) (.*)/
        challenge = $2
        params = {}
        challenge.gsub(/(\w+)="(.*?)"/) { params[$1] = $2 }

        a_1 = "#{@username}:#{params['realm']}:#{@password}" #username, realm and password
        a_2 = "#{httpmethod}:#{uri}" #method and path
        request_digest = '' request_digest << Digest::MD5.hexdigest(a_1)
        request_digest << ':' << params['nonce']
        request_digest << ':' << ('%08x' % @@nonce_count)
        request_digest << ':' << @cnonce
        request_digest << ':' << params['qop']
        request_digest << ':' << Digest::MD5.hexdigest(a_2)

        header = []
        header << "Digest username=\"#{@username}\""
        header << "realm=\"#{params['realm']}\""
        header << "qop=#{params['qop']}"
        header << "algorithm=MD5"
        header << "uri=\"#{uri}\""
        header << "nonce=\"#{params['nonce']}\""
        header << "nc=#{'%08x' % @@nonce_count}"
        header << "cnonce=\"#{@cnonce}\""
        header << "response=\"#{Digest::MD5.hexdigest(request_digest)}\""
        header << "opaque=\"#{params['opaque']}\""
        header_auth_str = header.join(', ')

# Build request (allows reuse)
    def build_request()
        @http = Net::HTTP.new(@uri.host, @uri.port)
        @http.use_ssl = true
        @http.verify_mode = OpenSSL::SSL::VERIFY_NONE
    end

# We need to get a response with a WWW-Authenticate request header
    def get_auth_response(uri)
        url = BASE_URL + uri
        @uri = URI.parse(url)
        build_request()
        req = Net::HTTP::Get.new(@uri.request_uri)
        response = @http.request(req)
        return response
    end

Good Luck!

Android – Figuring out the Mobile Network programmatically

On building an Android app for a specific mobile operator, I was once faced with the problem of making sure the phone running the app would have a SIM connected to that particular operator. Since the app I built functions completely independently from the mobile operator, I needed to figure out a solution to stop users on other networks from using it to ensure exclusivity for my client.

The obvious solution to this (at least, the solution which I thought of first) is to check the SIM’s mobile number, do some parsing and then figure out which operator the SIM is on. However, turns out nowadays the mobile phone number is not stored on the SIM card like it was in the old days. It is assigned dynamically by the mobile service provider, and this is why when you lose your SIM card you can simply get a new one with the old number assigned to it.

The method I used to get this done is using the checking the Mobile Country Code (MCC) + Mobile Network Code (MNC) combination that can be gained through a call to the TelephonyManager class’s getSimOperator method.

Code is as follows:

import android.telephony.TelephonyManager;
  TelephonyManager tMgr =  (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
  String operator = tMgr.getSimOperator(); // this returns the MCC+MNC
/* Do whatever checks you need here */

The above code will return the MCC + MNC composite for you. For Sri Lanka, the MCC is 413 and the MNCs are as follows:

  • Mobitel – 01
  • Dialog – 02
  • Etisalat – 03
  • Airtel – 05
  • Hutch – 08

For more information on MCCs and MNCs, you can go to the Wikipedia article.