Sprite Kit - Detecting Y due to an impulse and Gravity, if the ball is moving away or Closer to the ground

吃可爱长大的小学妹 提交于 2019-12-25 02:47:53

问题


I'm creating a false shadow for an SKSpriteNode (a Ball) with physicsBody and impulse in Y direction applied to it. I like to decrease the opacity of the shadow which stays on the ground as the ball raise and decrease it back to 100% as it heads back toward the ground. any Idea?


回答1:


Yes, use the update method. Then simply test the balls Y position on every update.

  1. Add the ball to your scene.
  2. Add a shadow to your scene.
  3. In the update method of your scene (called at every frame by SpriteKit) move the shadow to the correct coordinate. (Y level of that which the shadow is hitting, X of the ball).
  4. Set the opacity to (300.0-ball.position.y/300.0). 300.0 being the height where the shadow disappears completely.



回答2:


Below is a code sample. You can also use a SKAction to move the object up and down instead of doing it manually like I have in the update method. It all depends on your code and what works best for you.

#import "MyScene.h"

@implementation MyScene
{
    SKSpriteNode *object1;
    SKSpriteNode *shadow;
    BOOL goUp;
}

-(id)initWithSize:(CGSize)size
{
    if (self = [super initWithSize:size])
    {
        object1 = [SKSpriteNode spriteNodeWithColor:[SKColor redColor] size:CGSizeMake(50, 50)];
        object1.position = CGPointMake(100, 25);
        [self addChild:object1];

        shadow = [SKSpriteNode spriteNodeWithColor:[SKColor redColor] size:CGSizeMake(50, 50)];
        shadow.position = CGPointMake(200, 25);
        [self addChild:shadow];

        goUp = true;

    }
    return self;
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    //
}

-(void)update:(CFTimeInterval)currentTime
{
    if((goUp == true) && (object1.position.y == 200))
        goUp = false;

    if((goUp == false) && (object1.position.y == 25))
        goUp = true;

    if(goUp == true)
    {
        object1.position = CGPointMake(object1.position.x, object1.position.y+1);
        shadow.alpha -= 0.005;
    }

    if(goUp == false)
    {
        object1.position = CGPointMake(object1.position.x, object1.position.y-1);
        shadow.alpha += 0.005;
    }
}

@end


来源:https://stackoverflow.com/questions/23318129/sprite-kit-detecting-y-due-to-an-impulse-and-gravity-if-the-ball-is-moving-aw

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!