Jump to content

  • Log In with Google      Sign In   
  • Create Account

We're offering banner ads on our site from just $5!

1. Details HERE. 2. GDNet+ Subscriptions HERE. 3. Ad upload HERE.


array incrementation


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
2 replies to this topic

#1 proanim   Members   -  Reputation: 446

Like
0Likes
Like

Posted 21 February 2014 - 09:26 PM

I wanted to draw a grid with array of sprites. And I made it work with this code

// loop over each sprite, setting their textures
// grid
for(int i = 0; i < 20; i++)
{
	spr[i].setTexture(tex);
	spr[i].scale(sf::Vector2f(0.55f, 0.55f));

	// 1st row
	if(i < 10)
		spr[i].setPosition(105.6f * i, y);
	// 2nd row
	if(i > 10 || i < 20)
		spr[i+10].setPosition(105.6f * i, y + 52.8f);
	// 3rd row
	//if(i > 20 || i < 30)
	//	spr[i+20].setPosition(105.6f * i, y + 105.6f);

}

Now I want to optimize this code so I can use it more efficiently later. The code brakes if I set spr[i] instead of spr[i+10] in second if loop. Why is this? How can I continue through the array without +10 or whatever next to it?



Sponsor:

#2 Vortez   Crossbones+   -  Reputation: 2704

Like
4Likes
Like

Posted 21 February 2014 - 09:41 PM

You just need to learn to use the modulo operator.

 

for(int i = 0; i < 30; i++)
{
    spr[i].setTexture(tex);
    spr[i].scale(sf::Vector2f(0.55f, 0.55f));

 

    spr[i].setPosition(105.6f * (i % 10), y + (52.8f * (i / 10)));

}


Edited by Vortez, 21 February 2014 - 09:46 PM.


#3 aregee   Members   -  Reputation: 1026

Like
2Likes
Like

Posted 22 February 2014 - 09:36 AM

Vortez solution is the way to go, but it seems you have a flaw in your logic:

 

    if(i < 10) //This will be run if i is less than 10
    if(i > 10 || i < 20) //This will be run regardless
    if(i > 20 || i < 30) //This will be run regardless

What you have written is exactly the same as:

 

    if(i < 10) //This will be run if i is less than 10
    if(true) //This will be run regardless
    if(true) //This will be run regardless

I think this is what you meant:

    if(i < 10) //This will be run if i is less than 10
    if(i >= 10 && i < 20) //This will be run if i is greater or equal to 10, but less than 20
    if(i >= 20 && i < 30) //This will be run if i is greater or equal to 20, but less than 30

EDIT: Although operator precedence ensures the correct order of operation in this case, I usually wrap the tests like this for ease of reading:

    if ((i >= 20) && (i < 30))
But that is probably just taste...  smile.png

Edited by aregee, 22 February 2014 - 09:45 AM.





Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS