Keep track of sprite position in an array on update loop

。_饼干妹妹 提交于 2019-12-25 02:26:00

问题


Hi I have a loop adding monsters to an NSMutableArray

 - (void)addMonster:(CCTime)dt {


 _monster1 = [[Monster1 alloc] init];




for(int i=0;i<=num; i++)
{

    [spriteArray insertObject:_monster1  atIndex:num];

}

[_physicsWorld addChild:_monster1];


num++;
}

in my update loop this code is meant to check if each sprite has passed a certain point:

for (int i=0; i <= num; i++) 
{
    CCSprite *tempSprite = (CCSprite *) [spriteArray objectAtIndex:i];


    if (tempSprite.position.x > 100) {

    structurelife--;


    }

}

However this code isn't working (to decrease the int structurelife depending on how many monsters are passed that point, I'm pretty stuck so any help would be appreciated). The position of the Sprite remains at 0,0 even though it is moving accross the screen.


回答1:


Based on what your OP is trying to do and based on the code you wrote, your code is not correct. You state you are trying to add "monsters" to an array but instead what you are doing is adding pointers to the same monster to the array over and over again.

Your loop is essentially adding the same monster to it multiple times, rather than adding different monsters to the array. Whether it is the only problem with your code can't be determined by the small amount that was posted, but to start your method should look like this based on what you seem to be trying to do:

- (void)addMonster:(CCTime)dt
{
    for (int i=0; i<=num; i++)
    {
        Monster1 monster = [[Monster1 alloc] init];
        [spriteArray insertObject:monster atIndex:num];
        [_physicsWorld addChild:monster];
    }

    num++;
}

But again this is based on the code you have posted.

I hope this helped.



来源:https://stackoverflow.com/questions/24394073/keep-track-of-sprite-position-in-an-array-on-update-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!