我正在尝试在两个玩家之间创建游戏模拟。我想让他们通过键盘,通过根矩形的Keys.onPressed属性移动,但我遇到了一个问题,即两个玩家无法同时获得订单,因为只捕获了一个关键事件..这里是代码:
Rectangle
{
id: root
height: 1000; width: 1000
Row
{
spacing: 100
x: 350
Repeater
{
id: repeater
model: 2
Rectangle
{
width: 50
height: 100
y:500
color: "blue"
property int speedForward: 5
property int speedBackward: 3
Rectangle
{
height: 10; width: 10
x: 20
color: "red"
}
}
}
}
Keys.onPressed:
{
var robot = (event.key > 100) ? repeater.itemAt(0) : repeater.itemAt(1)
if((event.key === 16777234) || (event.key === 65))
{
robot.rotation = (robot.rotation - 5) % 360;
}
if((event.key === 16777236) || (event.key === 68))
{
robot.rotation = (robot.rotation + 5) % 360;
}
if((event.key === 16777235) || (event.key === 87))
{
robot.x = robot.x + robot.speedForward * Math.sin(Math.PI * robot.rotation / 180);
robot.y = robot.y - robot.speedForward * Math.cos(Math.PI * robot.rotation / 180);
}
if((event.key === 16777237) || (event.key === 83))
{
robot.x = robot.x - robot.speedForward * Math.sin(Math.PI * robot.rotation / 180);
robot.y = robot.y + robot.speedForward * Math.cos(Math.PI * robot.rotation / 180);
}
}
focus: true
}
任何想法?
答案 0 :(得分:4)
你应该使用Timer和Keys.onReleased
以下示例可以满足您的需求:
property var robot1Event: {"rotation":false,
"move":false};
property var robot2Event: {"rotation":false,
"move":false};
Keys.onPressed: {
if (event.key === Qt.Key_Left) { robot1Event["rotation"] = true; }
if (event.key === Qt.Key_Up) { robot1Event["move"] = true; }
if (event.key === Qt.Key_A) { robot2Event["rotation"] = true; }
if (event.key === Qt.Key_W) { robot2Event["move"] = true; }
}
Keys.onReleased: {
if (event.key === Qt.Key_Left) { robot1Event["rotation"] = false; }
if (event.key === Qt.Key_Up) { robot1Event["move"] = false; }
if (event.key === Qt.Key_A) { robot2Event["rotation"] = false; }
if (event.key === Qt.Key_W) { robot2Event["move"] = false; }
}
Timer {
interval: 50;
running: true;
repeat: true;
onTriggered: {
var rotation = function (robot) { robot.rotation = (robot.rotation - 5) % 360; }
var move = function (robot) {
robot.x = robot.x + robot.speedForward * Math.sin(Math.PI * robot.rotation / 180);
robot.y = robot.y - robot.speedForward * Math.cos(Math.PI * robot.rotation / 180);
}
var robot = repeater.itemAt(0);
if (robot1Event["rotation"]) { rotation(robot); }
if (robot1Event["move"]) { move(robot); }
robot = repeater.itemAt(1);
if (robot2Event["rotation"]) { rotation(robot); }
if (robot2Event["move"]) { move(robot); }
}
}