我想实现一个零重力世界,用鼠标可以拖拽世界各地的物体。
import QtQuick 2.2
import Box2D 1.1
Rectangle {
width: 1000
height: 500
id: global
property bool dragged: false
property variant joint: null
property variant body: null
Component {
id: jointComponent
MouseJoint {
world: world
bodyA: anchor
dampingRatio: 0.8
target: Qt.point(350.0,200.0);
maxForce: 100
}
}
MouseArea {
id: mouseArea
onPressed: {
global.createJoint(mouse.x,mouse.y);
}
onReleased: {
global.destroyJoint();
}
onPositionChanged: {
if(global.dragged == true)
{
global.joint.target = Qt.point(mouse.x,mouse.y);
}
}
anchors.fill: parent
}
function createJoint(x,y) {
if(global.joint != null) destroyJoint();
var body = global.body;
if(body == null) return;
var mouseJoint = jointComponent.createObject(world);
mouseJoint.target = Qt.point(x,y);
mouseJoint.bodyB = body;
mouseJoint.maxForce = body.getMass() * 30.0;
global.dragged = true;
global.joint = mouseJoint;
}
function destroyJoint() {
if(global.dragged == false) return;
if(global.joint != null) {
global.dragged = false;
global.joint.destroy();
global.joint = null;
global.body = null;
}
}
World {
id: world
anchors.fill: parent
gravity: Qt.point(0,0)
Body {
id: anchor
x:300
y: 300
width: 10
height: 10
}
Body {
id: forrepeat
x: (40 + Math.random() * 720)
y: (40 + Math.random() * 520)
width: 100
height: 50
bodyType: Body.Dynamic
//rotation: Math.random() * 360
fixtures: Polygon {
density: .5
friction: 0
restitution: 0.5
vertices: [
Qt.point(0, 0),
Qt.point(0, 50),
Qt.point(100, 50),
Qt.point(100, 0)
]
categories: Polygon.Category10
collidesWith: Box.Category1 | Box.Category2 | Box.Category3 | Box.Category4
}
Rectangle {
anchors.fill: parent
color: Qt.rgba(Math.random(),Math.random(),Math.random(),Math.random())
border.color:Qt.rgba(Math.random(),Math.random(),Math.random(),Math.random())
smooth: true
}
MouseArea {
anchors.fill: parent
propagateComposedEvents: true
onPressed: {
global.body = parent
mouse.accepted = false
}
}
}
}
}
世界在X和Y中它的重力设置为0。然而,当我拿起任何一个物体时,它们在鼠标点击上很好,但是一旦我移动,物体就会旋转,只要我点击鼠标在对象内。如果我放开鼠标,它们就会开始失控。
理想情况下,我想用鼠标移动我的物体上只有一点点动作。如果它是一个矩形,比如说,然后定向对象,使矩形的右侧边缘朝向鼠标移动的方向。