Reputation: 23
I'm working on a small game to learn more xcode and objective-C.
I want to move my sprite along one axis while i am touching. I know how to use SKAction with moveBy, but the sprite stops moving when it reaches the stated distance.
I want the sprite to move untill the touch ends. Currently i'm only moving it along the x axis.
Upvotes: 0
Views: 1031
Reputation: 1
Here's what I did -- not sure if it's the most efficient method, but it works the way I want it to!
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
if (self.isFingerOnBowl)
{
UITouch *touch = [touches anyObject];
CGPoint touchLocation = [touch locationInNode:self];
moveBowlToPoint = [SKAction moveToX:(touchLocation.x) duration:0.01];
[_bowl runAction:moveBowlToPoint];
}
}
Upvotes: 0
Reputation: 386018
There are several ways you could do this.
Here's a simple one: in your touchesBegan:withEvent:
, set a flag to YES
in your scene indicating that the finger is down. In touchesEnded:withEvent:
, set the flag to NO
. In your scene's update:
method, if the flag is YES
, modify the sprite's position.
@implementation MyScene {
BOOL shouldMoveSprite;
SKNode *movableSprite;
NSTimeInterval lastMoveTime;
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
lastMoveTime = HUGE_VAL;
shouldMoveSprite = YES;
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
shouldMoveSprite = NO;
}
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
shouldMoveSprite = NO;
}
static CGFloat kSpriteVelocity = 100;
- (void)update:(NSTimeInterval)currentTime {
NSTImeInterval elapsed = currentTime - lastMoveTime;
lastMoveTime = currentTime;
if (elapsed > 0) {
CGFloat offset = kSpriteVelocity * elapsed;
CGPoint position = movableSprite.position;
position.x += offset;
movableSprite.position = position;
}
}
Another approach would be, when the touch begins, to attach a custom action (using +[SKAction customActionWithDuration:block:]
) to the sprite that moves it a little bit, and to remove the action when the touch ends.
Another approach would be to use the physics engine. When the touch begins, set the sprite's physicsBody.velocity
to a non-zero vector (or apply an impulse). When the touch ends, set the velocity back to CGVectorMake(0,0)
.
Upvotes: 1