我正在学习 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)
白板的微信
相关分类