Hi Alexandra,
maybe you want to rethink your physical concept. Basically there are two ways how to handle and use physic systems:
- Only use collision detection without physics effects (logic needs to be implemented by your own, which is kinda tricky) – which is your current approach.
- Use the complete physic system with real collisions and physical effects. Might be easier!
If you try approach two, you can see the StackTheBoxDemo which handels already boxes, such as your blocks which can be dragged and moved around with a Mouse Joint. You can restrict the movement direction by defining the correct target point. This is the MouseJoint from StackTheBoxDemo but with the restriction of movement only into x direction archieved in
onPositionChanged
.
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.targetPoint = Qt.point(mouseX, mouseY)
// connect the joint with the body
mouseJointWhileDragging.movingBody = selectedBody
// set the physicsWorld where the joint should be created
mouseJointWhileDragging.world = physicsWorld
}
}
onPositionChanged: {
// this check is necessary, because the user might also drag when no initial body was selected
if (mouseJointWhileDragging && selectedBody) {
mouseJointWhileDragging.targetPoint = Qt.point(mouseX, selectedBody.parent.parent.y)
}
}
onReleased: {
// if the user pressed a body initially, remove the created MouseJoint
if(selectedBody) {
selectedBody = null
if (mouseJointWhileDragging)
mouseJointWhileDragging.destroy()
}
}
}
Cheers,
David