applyImpulse 对 CGPoint SpriteKit [英] applyImpulse towards CGPoint SpriteKit

查看:9
本文介绍了applyImpulse 对 CGPoint SpriteKit的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 SpriteKit 的新手,游戏开发者,事实上我只是在学习.所以我到了一个点,我应该将一堆节点移动到用户点击位置.到目前为止,我一直在努力计算一个虚拟的直角三角形,并根据边得到角的 sin 和 cos.不幸的是,这让我产生了一种非常强烈的冲动,并没有真正考虑用户的点击位置.

I'm kind of a newb in SpriteKit, game dev, as a matter of fact I'm just learning. So I got to a point where I what to move a bunch of nodes towards a users tap location. So far I fought that I might calculate a virtual right triangle and get sin and cos of angles based on the sides. Unfortunately that left me with a very strong impulse that doesn't really consider the user tap location.

有什么想法吗?

提前致谢.

推荐答案

在此处查看 Ray Wenderlich 教程中的射弹部分:

Look up the shooting projectiles section in the tutorial by Ray Wenderlich here:

http://www.raywenderlich.com/42699/spritekit-tutorial-初学者

将教程中的代码更改如下:

Change the code from the tutorial as follows:

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

    // 1 - Choose one of the touches to work with
    UITouch * touch = [touches anyObject];
    CGPoint location = [touch locationInNode:self];

    // 2 - Set up initial location of projectile
    SKSpriteNode * projectile = [self childNodeWithName:@"desirednode"];
    //make projectile point to your desired node.

    // 3- Determine offset of location to projectile
    CGPoint offset = rwSub(location, projectile.position);

    // 4 - Bail out if you are shooting down or backwards. You can ignore this if required.
    if (offset.x <= 0) return;

    // 5 - OK to add now - we've double checked position
    [self addChild:projectile];

    // 6 - Get the direction of where to shoot
    CGPoint direction = rwNormalize(offset);

    // 7 - Make it shoot far enough to be guaranteed off screen
    float forceValue = 200; //Edit this value to get the desired force.
    CGPoint shootAmount = rwMult(direction, forceValue);

    //8 - Convert the point to a vector
    CGVector impulseVector = CGVectorMake(shootAmount.x, shootAmount.y);
    //This vector is the impulse you are looking for.

    //9 - Apply impulse to node.
    [projectile.physicsBody applyImpulse:impulseVector];

}

代码中的 projectile 对象代表你的节点.此外,您需要编辑 forceValue 以获得所需的脉冲.

The projectile object in the code represents your node. Also, you will need to edit the forceValue to get the desired impulse.

这篇关于applyImpulse 对 CGPoint SpriteKit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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