HTML and CSS Reference
In-Depth Information
The wall sprites are created as normal Q.Sprite objects. (Remember these are Q.SVGSprite objects,
but calling svgOnly() during setup copies them to Q.Sprite .) Then their type is set to static to make
them nonmoving objects, and the physics component is added to them.
Next, six balls of different colors are added to the stage.
If you load this code in the browser, you should see six balls that fall vertically straight down.
Adding Orientation Control
To add in support for adjusting gravity relative to the device, add a deviceorientation event handler that
grabs the rotation data and adjusts the gravity vector in the Box2D world as necessary.
Because a beta and a gamma of 0 means that the device is laid flat and thus the ball shouldn't be moving, the
easiest way to adjust gravity is to multiply some constant by the sine of beta to get the y component of gravity
and by the sine of alpha to get the x component of gravity (from the perspective of the balls).
To add more excitement to the experience, the center block, stored in the center variable, is also rotated to
always face north (or alpha 0).
To try this, add the highlighted code in Listing 24-3 , as shown near the bottom of the orient.js file.
Listing 24-3: The orientation event handler
stage.viewport(400,600);
stage.centerOn(200,300);
if (window.DeviceOrientationEvent) {
$(window).on("deviceorientation",function(e) {
var eventData = e.originalEvent
tiltLR = eventData.gamma,
tiltFB = eventData.beta,
direction = eventData.alpha;
center.physics._body.SetAngle(direction * Math.PI / 180);
var leanAngle = tiltLR * Math.PI / 180,
tiltAngle = tiltFB * Math.PI /180,
gravityX = 20 * Math.sin(leanAngle),
gravityY = 20 * Math.sin(tiltAngle);
stage.world._world.m_gravity.x = gravityX;
stage.world._world.m_gravity.y = gravityY;
});
}
}));
If you run the example again in your browser on a supported mobile device or on Chrome in a recent
MacBook, you can play with the balls and adjust their movement by slightly rotating the device. (Up to the
point where the orientation flips, then all bets are off; the balls no longer follow gravity.)
 
 
 
Search WWH ::




Custom Search