如何在Sprite Kit,Objective C中用手指移动物体 [英] How to hit objects with finger movement in Sprite Kit, Objective C

查看:95
本文介绍了如何在Sprite Kit,Objective C中用手指移动物体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一款游戏,其中我有一些SKSpriteNodes,用户可以用手指移动它们,我正在使用苹果的新Sprite Kit。

为了做到这一点,我尝试了一个技巧 - 放置一个Sprite - 手指所在的X(SKSpriteNode),当用户移动手指时 - 改变这个X精灵的位置,

To do that I tried a trick - placing a Sprite - "X" (SKSpriteNode) where the finger is, and when the user moves the finger - change the position of this X sprite,

问题是它只会在没有运动的情况下击中其他精灵,我希望其他精灵响应移动手指的当前速度 - 手指移动得越快是 - 碰撞应该越强。

the problem is that it will hit the other sprites only if it's not in movement, I want the other sprites to respond to the current velocity of the moving finger- the faster the finger movement is- the stronger the collision should be.

你能帮助我吗?


  • 虽然我觉得诀窍不是正确的方法,但我也在发布代码。

  • Although I feel the trick is not the right way to do this,I'm posting the code too.

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    if([touches count]==1)
    {
        self.X= [[SKSpriteNode alloc]initWithImageNamed:@"X"];
        self.X.name= @"X";
        UITouch *t= touches.allObjects[0];          

        self.X.position= [t locationInNode:self.GameNode];
        self.X.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:20];
        self.X.physicsBody.dynamic=YES; // Tried NO too...
        self.X.zPosition=1;

        [self.GameNode addChild:self.X];
    }
}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *t = touches.allObjects[0];
    self.X.position = [t locationInNode:self.GameNode];
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.X removeFromParent];
}


推荐答案

在搜索并进行了大量实验后,我终于得到了答案!

After searching and making a lot of experiments, I finally have an answer!

解决方案的第一步是由AyatollahAndy - 找到影响点:

The first step in the solution was provided by AyatollahAndy - finding the point of impact:

SKNode *node = [self nodeAtPoint:location];

此行获取我们在指定位置点击的节点,如果它返回nil我们没有击中任何东西。

this line gets the node that we hit in the specified location, if it returns nil we didn't hit anything.

其次 - 我们想要击中对象,因此我们需要ApplyImpulse:

secondly- we want to "Hit" the object, therefor we need to ApplyImpulse:

[node.physicsBody applyImpulse:CGVectorMake(thrustV.x, thrustV.y) atPoint:location];

在这里你可以看到我使用我在影响点创建的一些向量来应用脉冲,
就是这样 - 很直接,我希望这会有所帮助。

Here you can see I applied the impulse with some vector that I created at the point of impact, That's it - pretty straight forward, I hope this will help others.

分享是关怀,
感谢您花时间阅读我的帖子。

Sharing is caring, Thanks for taking the time to read my post.

这篇关于如何在Sprite Kit,Objective C中用手指移动物体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆