Download

Is there a better way to ensure this check only occurs once per frame?

I have a function I use to for soft target lock which iterates through a list of nearby objects and guesses which one you’re trying to use based on distance and proximity to screen center. It’s very slightly expensive, so I want to ensure that it’s only called on frames where the player has either physically moved, or moved the camera. Right now I’m doing it like this:



	InputComponent->BindAxis("Turn", this, &AMCharacter::RequestAttention);
	InputComponent->BindAxis("Lookup", this, &AMCharacter::RequestAttention);
	InputComponent->BindAxis("MoveForward", this, &AMCharacter::RequestAttention);
	InputComponent->BindAxis("MoveRight", this, &AMCharacter::RequestAttention);


void AMCharacter::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);
	UpdateAttention();
}


void AMCharacter::UpdateAttention(){

	if (bCheckSurroundings){
		characterPerception->SetAttentionTarget(); //Calculate soft lock
                bCheckSurroundings = false;
	}
}

void AMCharacter::RequestAttention(float Value){
	if (Value != 0) //If the provided axis is recieving input...
		bCheckSurroundings = true; //request a new soft lock test
}

This works, but it’s really sloppy and wasteful: I check four axes every frame, and if the player is moving and looking around at the same time, which he pretty much always will be, I set the same boolean four times per frame, three of which are redundant. Is there any better way to detect when movement/mouselook is occurring, and only make a single call to SetAttentionTarget on that frame?

Looking at your code I can say it is absolutely ok. In terms of performance I doubt you will notice any slowdons even if you check a hundred of axes.

You could create a bool bWantsToDoTheCheck and change the key bindings to just set this to true.

In your tick, if the bool is true, do the heavy lifting and reset the bool to false. The bool just acts as a gate in this way to make sure you at most do some expensive thing once a frame.

Hard to improve on this, unless you combine it with other functions where you are guaranteed that the player or camera has moved (setting the boolean at that point in code).

Thats what his code does. :smiley:

I obviously didn’t read the description well enough. Setting the same bool 4 times a frame seems like a total non-issue.

You could Google pre-optimization and “root of all evil” for some opinions on that :wink:

Setting a bool happens in a single clock cycle to the only way to improve that is to never call the function in the first place. If you really want to measure it you could make a for loop that sets the bool X times and see what value of X starts to increase your frame time. I think you’d be surprised how high you’d have to go.