2013年おめでとう。
2 つの長方形の交差方法に少し問題がありますが、このトピックを進めることができないという問題につまずきました。
2 つの点と 2 つの四角形の 4 つのオブジェクトを使用しています。Point1 は矩形 1 の原点であり、Point2 は矩形 2 の原点です。
次に、rectangle1 の intersect メソッドを呼び出し、rectangle2 オブジェクトを送信して交差があるかどうかを確認します。
ここでの問題は、メソッド内で両方の長方形の原点が同じ座標になるため、原点が異なると良い情報が得られないことです。
ここに私の.hファイルがあります:
@interface XYPoint : NSObject
@property int x,y;
-(void) setX:(int)xVal andY: (int) yVal;
@end
@interface Rectangle: graphicObject
@property float width, height;
- (void) setWidth:(float)w andHeight: (float) h;
- (void) setOrigin: (XYPoint *) pt;
- (bool) containsPoint: (XYPoint *) aPoint;
- (void) intersect: (Rectangle *) rect;
@end
ここに私の.mファイルがあります:
@implementation XYPoint
@synthesize x,y;
-(void) setX:(int)xVal andY:(int)yVal;
{
x = xVal;
y = yVal;
}
@end
@implementation Rectangle
@synthesize width, height;
XYPoint *origin;
- (void) setWidth:(float) w andHeight: (float) h;
{
width = w;
height = h;
}
- (float) area
{
return width * height;
}
- (float) perimeter
{
return (2*width) + (2*height);
}
-(void) setOrigin: (XYPoint *) pt
{
if (! origin)
{
origin = [[XYPoint alloc]init];
}
origin.x = pt.x;
origin.y = pt.y;
}
- (XYPoint *) origin
{
return origin;
}
-(void) intersect: (Rectangle *) rect //
{
int pointCount;
pointCount = 0;
/* R1o R2o R1F R2F */
/* origin.x rect.origin.x origin.x+w rect.origin.x+w */
if ( (origin.x <= rect.origin.x) && (rect.origin.x <= (origin.x + width) ) )
pointCount = pointCount +1;
NSLog(@"width = %g height = %g origin = (%d,%d)", width, height, origin.x, origin.y);
NSLog(@"rect.width = %g rect.height = %g rect.origin (%d,%d)", rect.width, rect.height, rect.origin.x, rect.origin.y);
if ( (rect.origin.x <= ( origin.x + width ) ) && (origin.x + width <= rect.origin.x + rect.width) )
pointCount = pointCount + 1;
if ( (origin.y <= rect.origin.y) && (rect.origin.y <= (origin.y + height) ) )
pointCount = pointCount + 1;
if ( (rect.origin.y <= (origin.y + height) && ( origin.y + height <= rect.origin.y + rect.height)) )
pointCount = pointCount +1;
if (pointCount == 4)
NSLog (@"the rectangles intersect!");
else
NSLog (@"The rectangles don't intersect.");
}
@end
これは私のメインファイルです:
int main(int argc, const char * argv[])
{
@autoreleasepool {
Rectangle * myRectangle1 = [[Rectangle alloc] init];
XYPoint * myPoint1 = [[XYPoint alloc]init];
[myPoint1 setX: 0 andY: 0];
[myRectangle1 setWidth: 3 andHeight: 3];
[myRectangle1 setOrigin : myPoint1];
Rectangle * myRectangle2 = [[Rectangle alloc] init];
XYPoint * myPoint2 = [[XYPoint alloc]init];
[myPoint2 setX: 2 andY: 2];
[myRectangle2 setWidth: 4 andHeight: 4];
[myRectangle2 setOrigin : myPoint2];
[myRectangle1 intersect: myRectangle2];
}
return 0;
}
私が最後にそれを実行したとき、私はこれを持っています:
幅 = 3 高さ = 3 原点 = (2,2)
rect.width = 4 rect.height = 4 rect.origin (2,2)
四角が交差!
見る?設定が異なっていても、両方の長方形の原点は同じです。
どうもありがとう!