You are not logged in.

#1 2020-06-11 20:32:23

NunchuckBradley
Member
Registered: 2019-12-09
Posts: 2

Learning C++. Best practices for moving sprite?

I am learning C++ and I am doing a basic sprite character movement thing with sfml graphics.

I am able to make the character move using the controls and the sprite also changes correctly.

void changeSprite(float dt, int row, int column = 0){
			// time in seconds to change animation.
			if(spriteTime > 0.3 || spriteRow != row){
				spriteRow = row;
				int height = 48;
				int width = 32;
				spritePos.width = width;
				spritePos.height = height;
				int top = (row*height)-height;
				int left = (column*width)-width;
				spritePos.top = top;
				if(column == 0){
					if(spritePos.left == (3*width)){
	                                	spritePos.left = 0;
	                        	}
	                        	else{
	                        	        spritePos.left += width;
	                        	}
				}
				else{
					spritePos.left = left;
				}
				sprite.setTextureRect(spritePos);
				spriteTime = 0;
			}
			else{
				spriteTime += dt;
			}
		}

this code is the sprite visual change which is a member of a class. dt is from

float dt = clock.restart().asSeconds();

and in the while loop window.isOpen() also is below, to make the character move.

if(sf::Keyboard::isKeyPressed(sf::Keyboard::Up)){
			player.changeSprite(dt, 4);
			player.move(dt, 'u');
}

I am concerned that the practices used are bad. I set spriteTime and spriteRow multiple times and I feel like changing variables every 0.0002 seconds isnt good practice.

like the

int height

, if i have that outside the function, is it better for a computer then to have it inside the function?

If this were to run on an old system, would it have any effects maybe? Please tell me im wrong or help me get better. Thanks in advance

Last edited by NunchuckBradley (2020-06-11 20:42:35)

Offline

Board footer

Powered by FluxBB