PDA

View Full Version : How to make a sprite move?


MrPenguin9
10-26-2008, 12:18 PM
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:)

bovinedragon
10-26-2008, 01:33 PM
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?

MrPenguin9
10-26-2008, 02:07 PM
I can't figure out how to get the position of the sprite.

pmseltmann
11-04-2008, 05:50 AM
I can't figure out how to get the position of the sprite.

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.

moopf
11-04-2008, 06:17 AM
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.

pmseltmann
11-04-2008, 06:31 AM
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.

Thanks for the link moopf. I will also have to check that out.