0

I realize sprite kit is the way to go for games, but i was wondering if there was way using UIDynamicAnimator to set up additional constant forces besides gravity. I am making a platform game and have set the gravity downwards. I have sections of the screen setup to represent arrow keys (press the top of the screen to jump, sides to move left/right...). So far i have used the UIPushBehavior to jump and pulse left and right.

What i would like to do is have the view (player) constantly move left or right if the key is down. I would imagine that this would require a second sideways "gravity". I would turn this on when left section of the screen is touched and off when the touch is released. Any ideas on alternatives to this? Apparently you cannot make 2 gravities. I was thinking if you cant do 2 forces, maybe a way to set a constant speed for the view in a direction.

edit: i guess another way to phrase this would be... Is there a way to just straight up set the velocity for a view?

Undo
  • 25,519
  • 37
  • 106
  • 129
MingMan
  • 911
  • 1
  • 10
  • 31

1 Answers1

5

You can use a UIPushBehavior:

UIPushBehavior *pushBehavior = [[UIPushBehavior alloc] initWithItems:@[self.viewToAccelerate] mode:UIPushBehaviorModeContinuous];
pushBehavior.angle = M_PI_4;
pushBehavior.magnitude = 0.3;
[self.animator addBehavior:pushBehavior];

You just change the mode to UIPushBehaviorModeContinuous to make a constant force. Play with the magnitude and angle until it matches your needs. This will apply constant acceleration to your view.

Undo
  • 25,519
  • 37
  • 106
  • 129
  • thanks for the timely response. Ive tried that and it worked exactly as expected. Do you know of anyway to put a cap on speed? Like the game character can accelerate up to a max speed? – MingMan Mar 09 '14 at 21:35
  • @MingMan I'm not sure about that, but if you turn off the push behavior once your object reaches the speed you want and turn off friction, it should maintain that speed. – Undo Mar 09 '14 at 21:37
  • Right that makes sense. Ive been actually trying to find a way to get the views speed. Is that a real thing? – MingMan Mar 09 '14 at 21:41
  • Im dumb, i just found it. Thanks again for your help (btw for all those who want to know its "linearVelocityForItem:") – MingMan Mar 09 '14 at 21:42
  • You're welcome, @MingMan! Glad you found what you were after. – Undo Mar 09 '14 at 21:43