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

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

问题描述

我正在尝试制作一个游戏,其中我有一些 SKSpriteNodes 并且用户可以通过手指移动来点击它们,我正在使用苹果的新 Sprite Kit.

为此,我尝试了一个技巧——在手指所在的位置放置一个 Sprite——X"(SKSpriteNode),当用户移动手指时——改变这个 X sprite 的位置,

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天全站免登陆