Learn what Felgo offers to help your business succeed. Start your free evaluation today! Felgo for Your Business

BoxCollider

The BoxCollider is a physics body with a rectangular shape. More...

Import Statement: import Felgo 4.0
Inherits:

ColliderBase

Properties

Detailed Description

You can set the width and height to match the visual representation of the entity and define its physics properties for simulating physics behavior. If you only want to use the physics system for collision detection, set the ColliderBase::collisionTestingOnlyMode property to true. This component is derived from ColliderBase. See the ColliderBase documentation for a list and description of its properties that are also available for BoxCollider.

The origin of a BoxCollider is the top left point. If you want to shift the origin, adjust the x and y property or use anchors.centerIn: parent.

Example for Physics Used Only for Collision Detection

In the following example, the BoxCollider is only used for collision detection. That means, the physics properties are ignored. This is useful for games where the BoxCollider should not have a gravity, and the position of the entity is set from non-physics components like MoveToPointHelper or NumberAnimation. In the example, a collision is detected with the Fixture::onBeginContact signal handler and the entity is moved from the initial x position 0 to 100 within 2 seconds.

 import Felgo
 import QtQuick
 GameWindow {

   PhysicsWorld {
     // set no gravity, the collider is not physics-based
   }

   Scene {

      EntityBase {

        entityId: "box1"
        entityType: "box"

        Image {
            id: boxImage
            source: "../assets/img/box.png"
        }

        BoxCollider {
          // the BoxCollider will not be affected by gravity or other applied physics forces
          collisionTestingOnlyMode: true

          // make the same size as the Image
          anchors.fill: boxImage

          fixture.onBeginContact: {
             // handle the collision and make the image semi-transparent
             boxImage.opacity = 0.5
          }
        }

        // moves the entity to x position 100 within 2 seconds
        NumberAnimation on x {
          to: 100
          duration: 2000
        }
      }
    }
 }

Example for Physics-Driven Entity Positioning

In this example, the box1 entity falls down and moves to the right, based on physics properties like the world gravity, the density, friction and linearVelocity of the entity and will bounce off other entities based on the restitution setting.

 import Felgo

 import QtQuick

 GameWindow {

   PhysicsWorld {
     // set to world gravity
     gravity.y: -9.81
   }

   Scene {

      EntityBase {
        entityId: "box1"
        entityType: "box"

        Image {
            id: boxImage
            source: "../assets/img/box.png"
        }
        BoxCollider {

        // these are the default physics property values, but they can be changed to match the desired physics behavior
         friction: 0.2
         restitution: 0

         bodyType: Body.Dynamic
         bullet: false
         angularDamping: 0
         linearDamping: 0
         fixedRotation: false

         // initially, move to the right as linearVelocity.x is set to 100
         linearVelocity: Qt.point(100, 0)

          // make the same size as the Image
          anchors.fill: boxImage

          fixture.onBeginContact: {
             // handle the collision and make the image semi-transparent
             boxImage.opacity = 0.5
          }
        }
      }
    }
 }

Useful Physics Functions

Normally, you will interact with the physics bodies to implement game logic code. The most useful function is Fixture::onBeginContact(), for detecting if 2 physics bodies collided with each other. However, there are more functions that are useful for game development.

Collision Handlers

Besides Fixture::onBeginContact, you can also use Fixture::onEndContact to detect when 2 colliders are getting out of contact. As multiple colliders may collide with each other over time, you can create a property to count the number of collided bodies to test when there is no further collision with the body. Consider this example:

 BoxCollider {

   // this property holds the number of collided physics bodies with this BoxCollider
   property int numCollisions: 0

   fixture.onBeginContact: numCollisions++
   fixture.onEndContact: numCollision--

 }

Fixture::onContactChanged can be used if the contact point between 2 physics bodies changes, which happens very frequently after the collision. In fact, it happens as often per second as the PhysicsWorld::updatesPerSecondForPhysics property value. So for performance reasons, only use this functions if you really need to do something with the changed contact point. Otherwise, you could also use a Timer object to do something repeatedly while the BoxCollider collides with another entity, like in the following example:

 BoxCollider {

   // this property holds the number of collided physics bodies with this BoxCollider
   property int numCollisions: 0

   fixture.onBeginContact: numCollisions++
   fixture.onEndContact: numCollision--

   // this calls the onTriggered() function every 100 ms if the collider collides with another physics body
   Timer {
     running: numCollisions>0
     duration: 100
     repeat: true
     onTriggered: {
       console.debug("this object collides with another, for instance decrease the health property of the entity")
     }
   }
 }

Physics Movement

There are several ways you can simulate physics movement. The easiest is to set a fixed linearVelocity to the collider like in the following example:

 BoxCollider {
   linearVelocity: Qt.point(5, 2)
 }

Another option for physics movement is to apply forces, torques or impulses to the body. You can use the properties ColliderBase::force, ColliderBase::torque and the functions Body::applyLinearImpulse(), Body::applyForce() or Body::applyTorque(). Here is an example to apply an impulse in the forward direction, so in the direction the entity is currently rotated to, when the "Up" key is pressed:

 EntityBase {
   entityType: "rocket"

   BoxCollider {
     id: boxCollider
     width: 100
     height: 50
   }

   // the focus is required so the keyboard press can be handled
   focus: true
   Keys.onUpPressed: {
     // localForwardVector points towards the forward direction - if rotated at 0 degrees, that is to the right
     var localForwardVector = boxCollider.body.toWorldVector(Qt.point(1500,0));

     boxCollider.body.applyLinearImpulse(localForwardVector, boxCollider.body.getWorldCenter());
   }
 }

And here the alternative with applying a force with the force property:

 EntityBase {
   entityType: "rocket"

   BoxCollider {
     id: boxCollider
     width: 100
     height: 50
   }

   // the focus is required so the keyboard press can be handled
   focus: true
   Keys.onUpPressed: {

     // start applying a force towards the current rotation
     boxCollider.force = Qt.point(1500,0)
   }
   Keys.onUpPressed: {

     // start applying a force in the backwards direction of the current rotation
     boxCollider.force = Qt.point(-1500,0)
   }
   Keys.onUpReleased: {
     boxCollider.force = 0
   }
   Keys.onDownReleased: {
     boxCollider.force = 0
   }
 }

If you want the physics body to follow the touch or mouse position, use a MouseJoint. In the following example, a MouseJoint is created at a mouse or touch press and connected to the physics body at the touch position. The body then gets pulled towards the touched position, also when the position changes. For the full example code, see the StackTheBox Demo.

 Scene {
       Component {
           id: mouseJoint
           MouseJoint {
               // make this high enough so the box with its density is moved quickly
               maxForce: 30000
               // The damping ratio. 0 = no damping, 1 = critical damping. Default is 0.7
               dampingRatio: 1
               // The response speed, default is 5
               frequencyHz: 2
           }
       }

       // when the user presses a box, move it towards the touch position
       MouseArea {
           anchors.fill: parent

           property Body selectedBody: null
           property MouseJoint mouseJointWhileDragging: null

           onPressed: {

               selectedBody = physicsWorld.bodyAt(Qt.point(mouseX, mouseY));
               console.debug("selected body at position", mouseX, mouseY, ":", selectedBody);
               // if the user selected a body, this if-check is true
               if(selectedBody) {
                   // create a new mouseJoint
                   mouseJointWhileDragging = mouseJoint.createObject(physicsWorld)

                   // set the target position to the current touch position (initial position)
                   mouseJointWhileDragging.target = Qt.point(mouseX, mouseY)

                   // connect the joint with the body
                   mouseJointWhileDragging.bodyB = selectedBody
               }
           }

           onPositionChanged: {
               // this check is necessary, because the user might also drag when no initial body was selected
               if (mouseJointWhileDragging)
                   mouseJointWhileDragging.target = Qt.point(mouseX, mouseY)
           }
           onReleased: {
               // if the user pressed a body initially, remove the created MouseJoint
               if(selectedBody) {
                   selectedBody = null
                   if (mouseJointWhileDragging)
                       mouseJointWhileDragging.destroy()
               }
           }
       }

       Box {
           entityId: "box1"
           x: scene.width/2
           y: 50 // position a bit to the bottom so it doesn't collide with the top wall
       }
 }

Property Documentation

categories : CategoryFlags

The properties categories, collidesWith and groupIndex are used for collision filtering. That is useful if you want only some of your fixtures to collide with each other. By default, all fixtures collide with each other, so the default categories is Category1. The default collidesWith is All, and the default groupIndex is 0.

For example, say you make a character that rides a bicycle. You want the bicycle to collide with the terrain and the character to collide with the terrain, but you don't want the character to collide with the bicycle (because they must overlap). Therefore Box2D supports such collision filtering using categories and groups.

Box2D supports 16 collision categories. For each fixture you can specify which category it belongs to. You also specify what other categories this fixture can collide with. For example, you could specify in a game that all players don't collide with each other and enemies don't collide with each other, but players and enemies should collide. You might also have powerups in your game, with which the player should be able to collide, but not the monsters. This can be done with masking bits. For example:

 Scene {
   EntityBase {
     entityType: "player"

     BoxCollider {
       categories: Box.Category1
       // collide with enemies and powerups
       collidesWith: Box.Category2 | Box.Category3
     }
   }

   EntityBase {
     entityType: "enemy"

     BoxCollider {
       categories: Box.Category2
       // collide with players
       collidesWith: Box.Category1
     }
   }

   EntityBase {
     entityType: "powerup"

     BoxCollider {
       categories: Box.Category3
       // collide with players
       collidesWith: Box.Category1
     }
   }
 }

The groupIndex can also be used to choose fixtures that collide with each other: Fixtures with the same positive group index will always collide, regardless of their categories or collidesWith settings. Fixtures with the same negative groupIndex will never collide, regardless of categories or collidesWith.

Note: Only dynamic bodies collide with others. So 2 static bodies or 2 kinematic bodies can never collide with each other. When you use Joints to connect 2 fixtures, you can enable or disable collisions between these connected fixtures.

See also Fixture::categories, Fixture::collidesWith, and Fixture::groupIndex.


collidesWith : CategoryFlags

See the categories property documentation.


density : real

This property holds the density in kg/pixel^2. The fixture density is used to compute the mass properties of the parent body. The density can be 0 or positive. You should generally use similar densities for all your fixtures. This will improve stacking stability.

The default value is 0. The masses of all fixtures of a Body get added for dynamic bodies. If none of the fixtures of a body has a density set, the default body mass is set to 1kg.

Consider that static and kinematic bodies internally do not have a mass, so setting the density for them is useless.

If you want to make objects fall down faster, increase the PhysicsWorld::gravity property.

See also Fixture::density.


fixture : Fixture

This property alias allows access to the Box physics shape, which is called a fixture in Box2D.

Usually, you will not directly need to access this property, because you can access all fixture properties by the provided alias properties.


friction : real

Friction is used to make objects slide along each other realistically. It is usually in the range [0,1]. The default value is 0.2. A friction value of 0 turns off friction and a value of 1 makes the friction strong. If any of 2 colliding shapes has 0 friction, the resulting friction is 0 as the friction values get multiplied.

See also Fixture::friction.


groupIndex : CategoryFlags

See the categories property documentation.


restitution : real

Restitution is used to make objects bounce, so to simulate elastic objects like a rubber ball. It is usually in the range [0,1]. The default value is 0. Consider dropping a ball on a table. A value of zero means the ball won't bounce. This is called an inelastic collision. A value of one means the ball's velocity will be exactly reflected. This is called a perfectly elastic collision. The resulting restitution of 2 colliding shapes will be the maximum value.

See also Fixture::restitution.


sensor : bool

Set this property if you do not want the shape to react to collisions. This is useful if you only want to know that a collision happened, but not physically respond to it. The default value is based on the collisionTestingOnlyMode property - if it is set to true, the sensor flag also is set to true, otherwise to false.

See also Fixture::sensor.


Qt_Technology_Partner_RGB_475 Qt_Service_Partner_RGB_475_padded