Reputation: 105
I'm trying to create a game using qt. I have some obstacles (QPixmapItem) in a graphics view. I have a ball, and what I want is that it bounces off the obstacles. How can I detect the normal of the surface of the obstacle, so that I can calculate the new moving direction? For example:
------------------------------
/ \ |
/ \ |
/ \ v
/ \ ^
/ \ |
Upvotes: 3
Views: 1452
Reputation: 383
Based on your comments, you are indeed approaching the problem correctly. What you need to get to the solution however is to iterate over the QPainterPath elements and determine which ones actually intersect with your ball's direction line(using QLineF for this should be a fairly easy task). Also, simplifying the path will reduce any bezier curves to straight lines for easier calculations(I will leave this up to you as it's not likely you will need to handle the bezier calculation yourself or possibly at all). Since there may be more than one intersection, next you will need to determine which intersection point is closest to your ball's center. Once you've figured out which point is closest, use that element in a QLineF to find it's normal vector and then you can complete your calculation of the bounce direction.
Here is some basic non-threaded code to show you how to iterate a QPainterPath and handle it's elements.
QPainterPath path = item->shape();
path = path.simplified(); //optional if you do not want to handle curveTo elements yourself
QPainterPath::Element element;
QPainterPath::Element P1;
QPainterPath::Element P2;
QPainterPath::Element P3;
QPainterPath::Element P4;
for(int i = 0; i < path.elementCount()-1; ++i)
{
element = path.elementAt(i);
if(element.isMoveTo())
{
//Do something
}
else if(element.isLineTo())
{
//Do something with element.x and element.y
}
else if(element.isCurveTo())
{
P1 = path.elementAt(i-1); // start point
P2 = path.elementAt(i); // control point
P3 = path.elementAt(i+1); // control point
P4 = path.elementAt(i+2); // end point
//Do something with cubic bezier points
}
}
Upvotes: 1