How to make a sprite move?

Discussion in 'Public Game Developers Forum' started by MrPenguin9, Oct 26, 2008.

  1. MrPenguin9

    MrPenguin9 Active Member

    Jul 21, 2008
    30
    0
    0
    Hi, I am new to programing for the iPhone. I want to make a simple game where there is a button "Right" and a button "Left", and when you press the button the sprite moves. And when you let go of the button, the sprite stops moving. And I can't figure out how to make it move.

    Thanks so much:)
     
  2. bovinedragon

    bovinedragon Well-Known Member

    Sep 20, 2008
    98
    0
    0
    Just store the position of the sprite in a variable(eg float x,y;), and then every frame decide which button is being pressed(set up the appropriate functions to detect touches, and then check which button they are over). Then just increment the appropriate variable however fast you want it to go.

    The detecting touches is the harder part, is that where you are stuck?
     
  3. MrPenguin9

    MrPenguin9 Active Member

    Jul 21, 2008
    30
    0
    0
    I can't figure out how to get the position of the sprite.
     
  4. pmseltmann

    pmseltmann Well-Known Member

    Oct 21, 2008
    129
    0
    0
    Software Engineer
    San Diego, California
    What are you using for the sprite? Is it a UIView, CALayer or Texture2d?
    To get the position it should be something like:
    sprite.frame.origin.x and sprite.frame.origin.y

    or you can assign a CGPoint to sprite.frame.origin

    (A CGPoint is just a struct with an x and y coordinate).

    You can also get the center of the frame:

    CGPoint newCenter= sprite.center;

    ex:
    // Create empty blank sprite. In reality you'd add an image or something.
    UIImageView *sprite=[[UIImageView alloc] initWithFrame:CGRectMake(0,0,100,100)]];

    // Get the current center x,y location
    CGPoint newCenter = sprite.center;

    // Move the new center point 5 pixels
    newCenter.x+=5;

    // assign the new center point back to the original sprite.
    sprite.center=newCenter;

    That should move the sprite to the right 5 pixels.
     
  5. moopf

    moopf Well-Known Member

    Sep 16, 2008
    224
    1
    0
    This might not be what you're after but it may be worth checking out the cocos2d framework (http://code.google.com/p/cocos2d-iphone/) - it's a neat framework for 2D games that makes a lot of the leg work easier. I haven't used it in anger yet, but it looks extremely promising.
     
  6. pmseltmann

    pmseltmann Well-Known Member

    Oct 21, 2008
    129
    0
    0
    Software Engineer
    San Diego, California
    Thanks for the link moopf. I will also have to check that out.
     

Share This Page