[英]Drawing triangles in Cocoa
我正在开发一个简单的游戏,其中包含一个可以扔出绳索的精灵。 为了实现这一点,我希望用户单击屏幕上的一个点,并计算单击的点(目标)和播放器精灵位置(原点)之间的角度。 由此,我可以轻松地绘制直角三角形,然后我想限制三角形的斜边以表示“绳”的长度有限。
为此,我得到了原始的三角形角度,将其斜边定义为绳索的长度,然后使用余弦求出缩短的x长度,并使用正弦求出缩短的y高度。
当我试图找出答案时,我正在使用SKShapeNodes绘制临时三角形:
CGPoint origin = CGPointMake(0, 0);
CGPoint target = newAnchorPoint; //This the the clicked spot
CGPoint diff = CGPointMake(target.x - origin.x, target.y - origin.y);
double angle = atan2(diff.y,diff.x);
double kLength = 400;
double newXLength = cos(angle) * kLength;
double newYLength = sin(angle) * kLength;
CGPoint newTarget = CGPointMake(newXLength, newYLength);
tPath1 = CGPathCreateMutable();
CGPathMoveToPoint(tPath1, NULL, origin.x, origin.y);
CGPathAddLineToPoint(tPath1, NULL, target.x, origin.y);
CGPathAddLineToPoint(tPath1, NULL, target.x, target.y);
CGPathAddLineToPoint(tPath1, NULL, origin.x, origin.y);
tri1.path = tPath1;
tPath2 = CGPathCreateMutable();
CGPathMoveToPoint(tPath2, NULL, origin.x, origin.y);
CGPathAddLineToPoint(tPath2, NULL, newTarget.x, origin.y);
CGPathAddLineToPoint(tPath2, NULL, newTarget.x, newTarget.y);
CGPathAddLineToPoint(tPath2, NULL, origin.x, origin.y);
tri2.path = tPath2;
ang.path = nil;
CGMutablePathRef curve = CGPathCreateMutable();
CGPathAddArc(curve, NULL, origin.x, origin.y, 100, angle, 0, YES);
ang.path = curve;
问题是当原点为0,0时,它可以完美工作。 一旦原点从该点移开,第二个受约束的三角形将与原始三角形不匹配。 我已经检查并重新检查了数学,并确保我了解三角函数,但是我不明白为什么它的行为不符合预期。 任何帮助将非常感激。
您对newTarget
计算将产生代表绳索长度的向量。 相反, target
是位置。
我想您会想要:
CGPoint newTarget = CGPointMake(newXLength + origin.x, newYLength + origin.y);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.