我正在学习 Python,并想用 PyQ5t 制作一个简单的平台游戏。目前,当我想在游戏中的形状之间进行像素级碰撞检测时,我遇到了麻烦。我已将 QPixMap 设置为透明,并尝试使用 QGraphicsPixmapItem.HeuristicMaskShape 形状模式,但碰撞检测不起作用。
如果我将形状(在这种情况下为鼠标)背景设为灰色并删除形状模式,则会发生矩形碰撞检测。
我在这里缺少什么?我花了几个小时在互联网上挖掘,但还没有解决方案......
这是我显示问题的代码,请使用箭头键移动红色的“鼠标”:) 我希望在红色圆圈中的第一个像素接触棕色平台时看到碰撞检测文本。
import sys
from PyQt5.QtGui import QPen, QBrush
from PyQt5 import QtCore, QtGui
from PyQt5.QtCore import Qt, QPoint
from PyQt5.QtWidgets import QApplication, QWidget, QGraphicsView, QGraphicsScene, QLabel, QGraphicsPixmapItem, QFrame
class Mouse(QGraphicsPixmapItem):
def __init__(self, parent):
super().__init__()
self.canvas = QtGui.QPixmap(40,40)
self.canvas.fill(Qt.transparent)
self.setPixmap(self.canvas)
self.x = 100
self.y = 100
self.setPos(self.x, self.y)
self.setFlag(QGraphicsPixmapItem.ItemIsMovable)
self.setFlag(QGraphicsPixmapItem.ItemIsFocusable)
self.setShapeMode(QGraphicsPixmapItem.HeuristicMaskShape)
self.setFocus()
parent.addItem(self)
def paint(self, painter, option, widget=None):
super().paint(painter, option, widget)
pen = QPen(Qt.black, 4, Qt.SolidLine)
brush = QBrush(Qt.red, Qt.SolidPattern)
painter.save()
painter.setPen(pen)
painter.setBrush(brush)
painter.drawEllipse(QPoint(20,20),16,16)
painter.restore()
def keyPressEvent(self, e):
if e.key() == Qt.Key_Right:
self.x += 5
if e.key() == Qt.Key_Left:
self.x -= 5
if e.key() == Qt.Key_Up:
self.y -= 5
if e.key() == Qt.Key_Down:
self.y += 5
self.setPos(self.x, self.y)
collides_with_items = self.collidingItems(mode=Qt.IntersectsItemShape)
if collides_with_items:
print("Collision detected!")
for item in collides_with_items:
print(item)
class Platform(QFrame):
PLATFORM_STYLE = "QFrame { color: rgb(153, 0, 0); \
background: rgba(0,0,0,0%); }"
def __init__(self, parent, x, y, width, height):
super().__init__()
self.setGeometry(QtCore.QRect(x, y, width, height))
self.setFrameShadow(QFrame.Plain)
self.setLineWidth(10)
self.setFrameShape(QFrame.HLine)
self.setStyleSheet(Platform.PLATFORM_STYLE)
parent.addWidget(self)
class GameScreen(QGraphicsScene):
def __init__(self):
super().__init__()
# Draw background
background = QLabel()
background.setEnabled(True)
background.setScaledContents(True)
background.setGeometry(0, 0, 1280, 720)
background.setPixmap(QtGui.QPixmap("StartScreen.png"))
background.setText("")
background.setTextFormat(QtCore.Qt.RichText)
self.addWidget(background)
self.line_5 = Platform(self, 0, 80, 431, 16)
self.mouse = Mouse(self)
class Game(QGraphicsView):
def __init__(self):
super().__init__()
self.setWindowTitle("Running Mouse")
self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.gamescreen = GameScreen()
self.setScene(self.gamescreen)
self.show()
if __name__ == '__main__':
app = QApplication([])
game = Game()
sys.exit(app.exec_())