gpt4 book ai didi

objective-c - 在 Cocoa 中绘制三角形

转载 作者:行者123 更新时间:2023-12-03 17:21:38 25 4
gpt4 key购买 nike

我正在开发一个简单的游戏,其中涉及一个 Sprite 能够扔出一根绳子。为了实现这一点,我希望用户单击屏幕上的一个点,并计算单击的点(目标)和玩家 Sprite 位置(原点)之间的角度。由此我可以轻松地画出一个直角三角形,然后我想约束三角形的斜边来表示“绳子”的长度有限。

为此,我获取原始三角形角度,将其斜边定义为绳索的长度,然后使用余弦计算出缩短的 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);

关于objective-c - 在 Cocoa 中绘制三角形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24253202/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com