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

StackOverflow https://stackoverflow.com/questions/23318129

Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top