BoxCollider

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

Import Statement: import VPlay 2.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 VPlay 2.0
 import QtQuick 2.0
 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 VPlay 2.0

 import QtQuick 2.0

 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
       }
 }

These are the physics-based movement options. For a detailed tutorial of these options and for movement without physics see How to Move Entities & Objects with V-Play.

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.


Voted #1 for:

  • Easiest to learn
  • Most time saving
  • Best support

Develop Cross-Platform Apps and Games 50% Faster!

  • Voted the best supported, most time-saving and easiest to learn cross-platform development tool
  • Based on the Qt framework, with native performance and appearance on all platforms including iOS and Android
  • Offers a variety of plugins to monetize, analyze and engage users
FREE!
create apps
create games
cross platform
native performance
3rd party services
game network
multiplayer
level editor
easiest to learn
biggest time saving
best support
Sign up for Free and start developing right away!
I want to make Games
I want to make Apps
Game Development
Cross-Platform, Any Resolution

Use one IDE to deploy to all supported platforms, including iOS and Android, from a single code base.

Support all screen resolutions, aspect ratios and sizes with auto-adapting UI elements, smart scene scaling and memory efficient asset selection.

Learn More

V-Play ranked #1 at research2guidance cross-platform tool benchmarking 2014 by 2188 developers comparing 40 leading tools.

Multiplayer

V-Play Multiplayer supports both real-time and turn-based gameplay, so you can use it to make many different types of cross-platform multiplayer games. It's perfect for making player-vs-player games like 'Words with Friends' or games for a large amount of players, such as 'Clash of Clans'.

Learn More Video

Highscores & Achievements

The V-Play Game Network is a cross-platform gaming service that allows players around the world to compare game highscores and achievements. Players can also challenge each other across multiple platforms and share their progress on Facebook.

Learn More

QML & JavaScript

Qt Meta Language is a highly intuitive reactive language, which is super easy to learn, yet it's extremely powerful and flexible. Mix it with JavaScript to create awesome stuff, with just a few lines of code.

import QtQuick 2.0
import VPlay 2.0

GameWindow {
  Scene {
    
    SimpleButton {
      anchors.centerIn: parent
      text: "Press Me"
      onClicked: {
        console.debug("Wow you pressed me!")
      }
    }
  }
}

Learn More

Monetize & Analyze

With V-Play, you can use many 3rd party services for ads, in-app purchases, analytics and more, with just a few lines of code. All of these plugins work cross-platform, which allows you to maintain a single code base.

Learn More

Level Editor

The LevelEditor can be used during development to create and modify levels for your game, which you can then bundle in your final publishing build. Additionally, you can also integrate the in-game level editor to your published game and let your gamers create new levels.

Learn More Video

Card Game like UNO, Hearthstone or Poker

We got a demo game for you!

The V-Play SDK includes an open-source demo for this game genre. You can use its source code and build your game in record time. After installing V-Play, you can simply open the .pro file with Qt Creator, the development environment used for V-Play.

<Path to V-PlaySDK>/Examples/V-Play/demos/OneCard/OneCard.pro

Match-3 like Candy Crush Saga

We got a demo game for you!

The V-Play SDK includes an open-source demo for this game genre. You can use its source code and build your game in record time. After installing V-Play, you can simply open the .pro file with Qt Creator, the development environment used for V-Play.

<Path to V-PlaySDK>/Examples/V-Play/demos/JuicySquash/JuicySquash.pro

<Path to V-PlaySDK>/Examples/V-Play/demos/JuicySquashAdvanced/JuicySquashAdvanced.pro

Puzzle like 2048 or Threes!

We got a demo game for you!

The V-Play SDK includes an open-source demo for this game genre. You can use its source code and build your game in record time. After installing V-Play, you can simply open the .pro file with Qt Creator, the development environment used for V-Play.

<Path to V-PlaySDK>/Examples/V-Play/demos/2048/2048.pro

Casino like Big Win Slots

We got a demo game for you!

The V-Play SDK includes an open-source demo for this game genre. You can use its source code and build your game in record time. After installing V-Play, you can simply open the .pro file with Qt Creator, the development environment used for V-Play.

<Path to V-PlaySDK>/Examples/V-Play/demos/FlaskOfRum/FlaskOfRum.pro

Side Scroller like Jetpack Joyride or Flappy Bird

We got a demo game for you!

The V-Play SDK includes an open-source demo for this game genre. You can use its source code and build your game in record time. After installing V-Play, you can simply open the .pro file with Qt Creator, the development environment used for V-Play.

<Path to V-PlaySDK>/Examples/V-Play/demos/FlappyBird/FlappyBird.pro

Tower Defense like Castle Defense or Bloons TD

We got a demo game for you!

The V-Play SDK includes an open-source demo for this game genre. You can use its source code and build your game in record time. After installing V-Play, you can simply open the .pro file with Qt Creator, the development environment used for V-Play.

<Path to V-PlaySDK>/Examples/V-Play/demos/Squaby/Squaby.pro

Falldown & Jump like Doodle Jump or Mega Jump

We got a demo game for you!

The V-Play SDK includes an open-source demo for this game genre. You can use its source code and build your game in record time. After installing V-Play, you can simply open the .pro file with Qt Creator, the development environment used for V-Play.

<Path to V-PlaySDK>/Examples/V-Play/demos/ChickenOutbreak/ChickenOutbreak.pro

<Path to V-PlaySDK>/Examples/V-Play/demos/ChickenOutbreak2/ChickenOutbreak2.pro

<Path to V-PlaySDK>/Examples/V-Play/demos/DoodleJump/DoodleJump.pro

Platformer like Super Mario or Lep's World

We got a demo game for you!

The V-Play SDK includes an open-source demo for this game genre. You can use its source code and build your game in record time. After installing V-Play, you can simply open the .pro file with Qt Creator, the development environment used for V-Play.

<Path to V-PlaySDK>/Examples/V-Play/demos/Platformer/Platformer.pro

<Path to V-PlaySDK>/Examples/V-Play/demos/PlatformerWithLevelEditor/PlatformerWithLevelEditor.pro

Action like Angry Birds, Fruit Ninja, Cut the Rope

We got a demo game for you!

The V-Play SDK includes an open-source demo for this game genre. You can use its source code and build your game in record time. After installing V-Play, you can simply open the .pro file with Qt Creator, the development environment used for V-Play.

<Path to V-PlaySDK>/Examples/V-Play/demos/StackTheBoxWithCommunityEditor/StackTheBoxWithCommunityEditor.pro

<Path to V-PlaySDK>/Examples/V-Play/demos/BalloonPop/BalloonPop.pro

<Path to V-PlaySDK>/Examples/V-Play/demos/CarChallenge/CarChallenge.pro

Arcade like Arkanoid or Space Invaders

We got a demo game for you!

The V-Play SDK includes an open-source demo for this game genre. You can use its source code and build your game in record time. After installing V-Play, you can simply open the .pro file with Qt Creator, the development environment used for V-Play.

<Path to V-PlaySDK>/Examples/V-Play/demos/ZombieBreak/ZombieBreak.pro

Community like Super Mario Maker or Minecraft

We got a demo game for you!

The V-Play SDK includes an open-source demo for this game genre. You can use its source code and build your game in record time. After installing V-Play, you can simply open the .pro file with Qt Creator, the development environment used for V-Play.

<Path to V-PlaySDK>/examples/Squaby/Squaby.pro

<Path to V-PlaySDK>/Examples/V-Play/demos/StackTheBoxWithCommunityEditor/StackTheBoxWithCommunityEditor.pro

<Path to V-PlaySDK>/Examples/V-Play/demos/PlatformerWithLevelEditor/PlatformerWithLevelEditor.pro

Any other Idea? let us know how we can help you

You are looking for another demo?

The V-Play SDK includes many open-source demos for different game genres. You can use their source code and build your game in record time. After installing V-Play, you can simply open the .pro file with Qt Creator, the development environment used for V-Play.

If you do not find your game genre in this list and wonder if V-Play is the right choice, just contact us, we are happy to help!

Contact Us

App Development
Better Apps, Less Effort

Develop feature-rich, cross-platform mobile apps from a single code base.

V-Play apps look, feel and perform exactly like native iOS, Android and Desktop apps. With less code & much faster development time.

Learn More Highlights Video

V-Play ranked #1 at research2guidance cross-platform tool benchmarking 2014 by 2188 developers comparing 40 leading tools.

Save Time, Code & Money

Save up to 90% source code with V-Play, compared to frameworks like Xamarin, Titanium, React Native and others.

Learn More

QML & JavaScript

Qt Meta Language is a highly intuitive reactive language, which is super easy to learn, yet it's extremely powerful and flexible. Mix it with JavaScript to create awesome stuff, with just a few lines of code. QML also allows you to easily create smooth and complex animations.

import QtQuick 2.0
import VPlayApps 2.0

App {
  Page {
    
    AppButton {
      anchors.centerIn: parent
      text: "Press Me"
      onClicked: {
        console.debug("Wow you pressed me!")
      }
    }
  }
}

Learn More

Monetize & Analyze

With V-Play, you can use many 3rd party services for ads, in-app purchases, analytics and more, with just a few lines of code. All of these plugins work cross-platform, which allows you to maintain a single code base.

Learn More

Native Sensors & More

V-Play Apps harness the power of Qt, the leading cross-platform development framework used by over 1,000,000 developers.

This gives your access to native device features like sensors, camera, file system as well as multimedia, networking, localization and much more.

Learn More

Responsive Design

V-Play has built in responsive design capabilities, you can target phones and tablets with the same source code.

Learn More

Highly Extensible

You have existing JavaScript, C++ or native code? You want to add any 3rd party SDK that we do not offer already?

No worries, you can add any JS, C++, Java or Objective-C code to your project.

Learn More

Component Showcase App shows the most important V-Play features and components

We got a demo app for you!

The V-Play SDK includes an open-source demo for this app type. You can use its source code and build your app in record time. After installing V-Play, you can simply open the .pro file with Qt Creator, the development environment used for V-Play.

<Path to V-PlaySDK>/Examples/V-Play/appdemos/showcase/Showcase.pro

Qt World Summit Conference App a full-featured conference management app made by V-Play

We got a demo app for you!

The V-Play SDK includes an open-source demo for this app type. You can use its source code and build your app in record time. After installing V-Play, you can simply open the .pro file with Qt Creator, the development environment used for V-Play.

<Path to V-PlaySDK>/Examples/V-Play/appdemos/qtws2016/QtWS2016.pro

Twitter App how to build layouts like in the official Twitter app for iOS and Android

We got a demo app for you!

The V-Play SDK includes an open-source demo for this app type. You can use its source code and build your app in record time. After installing V-Play, you can simply open the .pro file with Qt Creator, the development environment used for V-Play.

<Path to V-PlaySDK>/Examples/V-Play/appdemos/twitter/Twitter.pro

Maps App displays free bikes or boxes at bike stations for Vienna's bike sharing service Citybike Wien

We got a demo app for you!

The V-Play SDK includes an open-source demo for this app type. You can use its source code and build your app in record time. After installing V-Play, you can simply open the .pro file with Qt Creator, the development environment used for V-Play.

<Path to V-PlaySDK>/Examples/V-Play/appdemos/maps/Maps.pro

Messaging App demonstrates how to create the UI of a Facebook Messenger like app

We got a demo app for you!

The V-Play SDK includes an open-source demo for this app type. You can use its source code and build your app in record time. After installing V-Play, you can simply open the .pro file with Qt Creator, the development environment used for V-Play.

<Path to V-PlaySDK>/Examples/V-Play/appdemos/messaging/Messaging.pro

Weather App how to include powerful animations into your user interface

We got a demo app for you!

The V-Play SDK includes an open-source demo for this app type. You can use its source code and build your app in record time. After installing V-Play, you can simply open the .pro file with Qt Creator, the development environment used for V-Play.

<Path to V-PlaySDK>/Examples/V-Play/appdemos/waether/Weather.pro

Any other Idea? let us know how we can help you

You are looking for another app demo?

The V-Play SDK includes many open-source demos for different app types. You can use their source code and build your app in record time. After installing V-Play, you can simply open the .pro file with Qt Creator, the development environment used for V-Play..

If you do not find your app type in this list and wonder if V-Play is the right choice, just contact us, we are happy to help!

Contact Us