# How can I move an object around the screen in cocos2d?

I am trying to move the object around the screen using cocos2d. I have this code:

-(void) move
{
CGFloat upperLimit = mWinSize.height - (mGunda.contentSize.height / 2.0);
CGFloat upperLimit1 = mWinSize.height;
CGFloat lowerLimit = (mGunda.contentSize.height / 2.0);
CGFloat RightLimit = mWinSize.width - (mGunda.contentSize.width/2.0);
CGFloat Right = (mGunda.contentSize.width/2.0);

if(mImageGoingUpward ) {
mGunda.position = ccp( mGunda.position.x, mGunda.position.y + 5);

if(mGunda.position.y >= upperLimit) {
mImageGoingUpward = NO;
mHori = NO;
}
} else {
mGunda.position = ccp( mGunda.position.x, mGunda.position.y - 5);
if(mGunda.position.y <= lowerLimit) {
mGunda.position = ccp(mGunda.position.x +5, lowerLimit);
}

if(mGunda.position.x >= RightLimit) {
mGunda.position = ccp(mGunda.position.x, mGunda.position.y+10);
mHori = YES;
}

if(mHori) {
if(mGunda.position.y >= upperLimit) {
mGunda.position = ccp(mGunda.position.x - 5,mGunda.position.y);
}
}
}
}


It is supposed to move the object around the screen. The code mostly works, but it doesn't move the object from the top-right of the screen to the left of the screen.

• you will propably have to explain what the ccp function does. And it would be nice if you format your code in some better way Jan 10 '11 at 13:45
• ccp is just a wrap for CGPointMake Feb 9 '11 at 19:37
• It's probably important to note that this code is using cocos2d. Also, could someone with edit powers please clean up the sample code? It's very hard to read!
– Olie
Sep 26 '11 at 15:04

## 2 Answers

it's basically because when you mark mHury as true, this statement if(mGunda.position.y >= upperLimit) is still not true.

Check through your logic - it is broken. To sum it up in English, assuming I got it right (your code is horribly indented and not C++ :P)

if going upwards then adjust position upwards and if we exceed some limit in y stop further upwards movement. else: lower the image (wtf???) if y is below some lower limit move it to the right (wtf???) if x is above some upper limit then move it upwards at double speed (again, wtf???) and set a flag to say we are moving horizontally if the horizontal flag is set and we have y exceeding some upper limit then move it to the left. (again, wtf???)

Maybe I am missing something, but this makes no sense to me. What are you actually trying to achieve and how is the requirement to move input to this code (e.g. who sets mImageGoingUpward - can mHori be set from outside, etc.)? It is not very obvious, which precludes a detailed and complete answer to the question.

• It's Objective-C code, not C++.
– user1430
Oct 10 '11 at 17:35
• Also this doesn't really answer the question.
– user1430
Oct 10 '11 at 17:40