Android game engine and engine Learning Series 6: physics physical collision effect understanding

Source: Internet
Author: User

 

See the example in exmaples: collisiondetectionexample and see the following:

 

In fact, this example is very similar to drawing a virtual game joystick. The difference is that there are two Sprite in the middle. The key statement for determining the collision is as follows:

Scene. registerupdatehandler (New iupdatehandler () {// register an updatehandler in the scenario. Every update is run once @ overridepublic void reset () {}@ overridepublic void onupdate (final float implements condselapsed) {If (centerrectangle. collideswith (FACE) {centerrectangle. setcolor (1, 0, 0); // If two sprite instances touch each other, the sprite becomes red} else {centerrectangle. setcolor (0, 1, 0); // if there is no touch, it turns blue }}});

In addition, mcamera. isrectangularshapevisiblE (FACE)Determine whether the face is beyond the camera's horizon.

 

 

Physics uses physical effects such as imitating gravity in the real world and hitting the wall. Here is a typical example: physicsexample.

The effect is as follows:

 

Implemented iaccelerometerlistener gravity acceleration, ionscenetouchlistener touch screen events, and other interfaces.

To achieve the physical effect, follow these steps:

1. Create a physical world

this.mPhysicsWorld = new PhysicsWorld(new Vector2(0, SensorManager.GRAVITY_EARTH), false);

 

2. Create a wall and load it to scene.

Final shape ground = new rectangle (0, camera_height-2, camera_width, 2); final shape Roof = new rectangle (0, 0, camera_width, 2 ); final shape left = new rectangle (0, 0, 2, camera_height); final shape right = new rectangle (camera_width-2, 0, 2, camera_height); Final fixturedef wallfixturedef = physicsfactory. createfixturedef (0, 0.5f, 0.5f); // The parameters are density, elasticity, and friction. Physicsfactory. createboxbody (this. mphysicsworld, ground, bodytype. staticbody, wallfixturedef); physicsfactory. createboxbody (this. mphysicsworld, roof, bodytype. staticbody, wallfixturedef); physicsfactory. createboxbody (this. mphysicsworld, left, bodytype. staticbody, wallfixturedef); physicsfactory. createboxbody (this. mphysicsworld, right, bodytype. staticbody, wallfixturedef); scene. getbottomlayer (). addentity (ground); scene. getbottomlayer (). addentity (roof); scene. getbottomlayer (). addentity (left); scene. getbottomlayer (). addentity (right );

3. register the physicsworld instance with scene. registerupdatehandler to the scenario.

scene.registerUpdateHandler(this.mPhysicsWorld);

4. After the physical world is created, a Sprite is created when the ionscenetouchlistener interface is implemented externally.

Public Boolean onscenetouchevent (final scene pscene, final touchevent pscenetouchevent) {If (this. mphysicsworld! = NULL) {If (pscenetouchevent. getaction () = touchevent. action_down) {This. runonupdatethread (New runnable () {@ overridepublic void run () {physicsexample. this. addface (pscenetouchevent. getx (), pscenetouchevent. gety (); // Note 1}); Return true ;}} return false ;}

After completing the preceding steps, you can complete the Collision Effect of the entire physical world.

 

Note 1: There are four different sprite collision walls in this example. The key statements are as follows:

if(this.mFaceCount % 4 == 0) {face = new AnimatedSprite(pX, pY, this.mBoxFaceTextureRegion);body = PhysicsFactory.createBoxBody(this.mPhysicsWorld, face, BodyType.DynamicBody, FIXTURE_DEF);} else if (this.mFaceCount % 4 == 1) {face = new AnimatedSprite(pX, pY, this.mCircleFaceTextureRegion);body = PhysicsFactory.createCircleBody(this.mPhysicsWorld, face, BodyType.DynamicBody, FIXTURE_DEF);} else if (this.mFaceCount % 4 == 2) {face = new AnimatedSprite(pX, pY, this.mTriangleFaceTextureRegion);body = PhysicsExample.createTriangleBody(this.mPhysicsWorld, face, BodyType.DynamicBody, FIXTURE_DEF);} else {face = new AnimatedSprite(pX, pY, this.mHexagonFaceTextureRegion);body = PhysicsExample.createHexagonBody(this.mPhysicsWorld, face, BodyType.DynamicBody, FIXTURE_DEF);}face.animate(200);face.setUpdatePhysics(false);scene.getTopLayer().addEntity(face);

There is nothing to say about the first and second types, which is similar to the syntax for creating walls above. The third and fourth types of triangle and hexagonal structures are complicated and need to be calculated. The principle is as follows:
First, let's look at the method of the triangle Sprite. First, we can get the width and height of the sprite Based on the triangle Sprite. Of course, here we will remove the width and height. For convenience of calculation, we can get the coordinates:

A (0,-h), B (-W, h), C (W, h ),

This is based on the android coordinate system. After obtaining the coordinate value, we can determine the vector2 class. The key is vertor2.

Let's take a look at the principle of the regular hexagonal:

Similarly, we can get W and H. According to the mathematical knowledge, the BG length is 0.5 * H. As for how to calculate the BG, you can ask the Middle School's mathematical teacher, so we can get the coordinates:

A (0,-h), B (W,-0.5 h), C (W, 0.5 h), D (0, h), E (-W, 0 ,. 5 H), F (-W,-0.5 h );

Now, we get the coordinates. we can define the vertor2 array:

Final vector2 [] vertices = {New vector2 (centerx, top), new vector2 (right, higher), new vector2 (right, lower), new vector2 (centerx, bottom ), new vector2 (left, lower), new vector2 (left, higher)}; // The Point sequence here is from vertex, then clockwise, that is, the abcdef sequence above.

The same is true for triangles. With vertices, We can get Sprite in different shapes in the physical world.

return PhysicsFactory.createPolygonBody(pPhysicsWorld, pShape, vertices, pBodyType, pFixtureDef);

The following describes how to create a hexagonal structure:

private static Body createHexagonBody(final PhysicsWorld pPhysicsWorld, final Shape pShape, final BodyType pBodyType, final FixtureDef pFixtureDef) {/* Remember that the vertices are relative to the center-coordinates of the Shape. */final float halfWidth = pShape.getWidthScaled() * 0.5f / PIXEL_TO_METER_RATIO_DEFAULT;final float halfHeight = pShape.getHeightScaled() * 0.5f / PIXEL_TO_METER_RATIO_DEFAULT;/* The top and bottom vertex of the hexagon are on the bottom and top of hexagon-sprite. */final float top = -halfHeight;final float bottom = halfHeight;final float centerX = 0;/* The left and right vertices of the heaxgon are not on the edge of the hexagon-sprite, so we need to inset them a little. */final float left = -halfWidth + 2.5f / PIXEL_TO_METER_RATIO_DEFAULT;final float right = halfWidth - 2.5f / PIXEL_TO_METER_RATIO_DEFAULT;final float higher = top + 8.25f / PIXEL_TO_METER_RATIO_DEFAULT;final float lower = bottom - 8.25f / PIXEL_TO_METER_RATIO_DEFAULT;final Vector2[] vertices = {new Vector2(centerX, top),new Vector2(right, higher),new Vector2(right, lower),new Vector2(centerX, bottom),new Vector2(left, lower),new Vector2(left, higher)};return PhysicsFactory.createPolygonBody(pPhysicsWorld, pShape, vertices, pBodyType, pFixtureDef);}

At first, I couldn't figure it out, that is, why do I add or subtract 2.5 from the left and right while defining coordinates, and why do I add or subtract 8.25 from the upper and lower sides? I can see the image after reading it, the pattern on the texture PNG map does not fill up the entire texture. The top, bottom, and left have some margins, as shown below:

The chart is magnified by me. To make it easier for you to see it clearly, you can see the question above. Why are there so many specific numbers, it must be related to pixels. If you are interested, you can find this image and then enlarge it and slowly count it. Then you will understand it!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.