★ TouchArcade needs your help. Click here to support us on Patreon.

How to make a sprite move?

10-26-2008, 11:18 AM
#1
Joined: Jul 2008
Posts: 30
How to make a sprite move?

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
10-26-2008, 12:33 PM
#2
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?
10-26-2008, 01:07 PM
#3
Joined: Jul 2008
Posts: 30
I can't figure out how to get the position of the sprite.
11-04-2008, 05:50 AM
#4
Joined: Oct 2008
Location: San Diego, California
Posts: 129
Send a message via AIM to pmseltmann
Quote:
Originally Posted by MrPenguin9 View Post
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.
11-04-2008, 06:17 AM
#5
Joined: Sep 2008
Posts: 224
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.

"Arthur & Charles Present Create & Play" now available on the App Store
iTunes - Arthur & Charles Website
11-04-2008, 06:31 AM
#6
Joined: Oct 2008
Location: San Diego, California
Posts: 129
Send a message via AIM to pmseltmann
Quote:
Originally Posted by moopf View Post
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.