我正在制作一款游戏,并希望我的一个精灵直接从玩家点击的地方移动。
[+] (tap location)
[+] (player)
在上面的例子中,玩家将向左和向下移动。
有人可以帮助我完成物理学吗?
我意识到我要使用三角学来计算角度,从而计算向量(对于applyImpulse:
),但是我对围绕玩家的每个象限都没有计算。
这是我的代码(在touchesBegan:
)
UITouch *touch = [touches.allObjects objectAtIndex:0];
CGPoint touchPosition = [touch locationInNode:self];
CGPoint playerPosition = self.playerBubble.position;
double oppositeLength = (touchPosition.y - playerPosition.y);
double adjacentLength = (touchPosition.x - playerPosition.x);
double angle = atan(oppositeLength / adjacentLength);
向量计算如下:
CGFloat playerMass = 0.0000013;
CGVector vector = CGVectorMake(playerMass * cosl(angle), playerMass * sinl(angle));
以下是玩家周围每个象限的矢量输出:
+,+ :
O: 133.000000, A: 42.500000, Angle: 72.278778, Theta: 1.261503
{3.9570166773706921e-07, 1.2383134543301224e-06}
- ,+ :
O: 95.247955, A: -79.580551, Angle: -50.120930, Theta: -0.874775
{8.335201515172361e-07, -9.9761925504652419e-07}
+, - :
O: -145.927795, A: 52.148361, Angle: -70.335281, Theta: -1.227582
{4.3747011829674742e-07, -1.2241813250586403e-06}
- , - :
O: -138.968933, A: -92.015755, Angle: 56.490189, Theta: 0.985940
{7.1770369806877642e-07, 1.0839286982100348e-06}
编辑:
这是我更新的答案,它给出了正确的向量(在SKSpriteNode实例上调用):
- (void)moveWithTouchPosition:(CGPoint)touchPosition
{
double heightLength = (self.position.y - touchPosition.y);
double widthLength = (self.position.x - touchPosition.x);
double angle = 0.0f;
if (touchPosition.y > self.position.y && touchPosition.x > self.position.x) {
//
// +, +
//
angle = M_PI + atan(heightLength / widthLength);
} else if (touchPosition.y > self.position.y && touchPosition.x < self.position.x) {
//
// -, +
//
angle = M_PI + M_PI_2 + atan(widthLength / heightLength);
} else if (touchPosition.y < self.position.y && touchPosition.x > self.position.x) {
//
// +, -
//
angle = M_PI_2 + atan(widthLength / heightLength);
} else if (touchPosition.y < self.position.y && touchPosition.x < self.position.x) {
//
// -, -
//
angle = atan(heightLength / widthLength);
}
CGVector vector = CGVectorMake(self.physicsBody.mass * cosl(angle), self.physicsBody.mass * sinl(angle));
[self.physicsBody applyImpulse:vector];
}
答案 0 :(得分:0)
为简化您的代码,您可以使用atan2而不是atan。 Atan2为你做象限。
另一个选择是翻译和乘法矢量而不是使用三角函数,这可能看起来像:
CGVector vector = CGVectorMake(
(playerPosition.x - touchPosition.x) * playerMass + touchPosition.x,
(playerPosition.y - touchPosition.y) * playerMass + touchPosition.y
);
答案 1 :(得分:0)
感谢@Bemmu,似乎我真正需要做的就是使用atan2(y,x)函数并解析三角形的Opp和Adj长度,它们分别是y和x值之间的差异。
E.g:
double heightLength = (self.position.y - touchPosition.y);
double widthLength = (self.position.x - touchPosition.x);
double angle = atan2(heightLength, widthLength);
CGFloat acceleration = 100.0f;
CGVector vector = CGVectorMake(self.physicsBody.mass * (cosl(angle) * acceleration), self.physicsBody.mass * (sinl(angle) * acceleration));
[self.physicsBody applyImpulse:vector];