Using gamepad stick for turret rotation

Hello,

just in case this might be interesting for someone else (or maybe I can get some feedbacks on how to make it more efficient).
I’m doing Rob’s course, but I’m aiming to use the left stick of the gamepad for aiming (more for experience than gameplay).

Hope it may be useful to someone else.
First, I’ve added the 2 axis binds for the X and Y axis of left gamepad’s stick. The result I’m storing in the variables angleOnX and angleOnY

I’ve overloaded the function RotateTurret to receive a FQuat as shown below:

void APawnBase::RotateTurret(FQuat Rotation)
{
	// adds rotation according to given quaternion
	TurretMesh->SetWorldRotation(Rotation);
}

And added these to the Tick method of APawnTank.

void APawnTank::Tick(float DeltaTime) 
{
        // ...
	if ((!FMath::IsNearlyEqual(0.0, angleOnX, 0.75)) 
		|| (!FMath::IsNearlyEqual(0.0, angleOnY, 0.75)))
	{
		const float actorFaceAngle = GetActorRotation().Yaw;
		// creates a vector for the joystick
		FVector joystickAngleVector(angleOnX, angleOnY, 0.);
		// find the cosine between the joystick angle against "forward" vector
		float angleCosine = joystickAngleVector.DotProduct(joystickAngleVector, FVector(0.,1.,0.));
		// find the angle in degrees 
		float angle = acos(angleCosine) * 180.f / 3.14159265f;
		// little patch to trick the angle, for this calculation, if X is negative, we must invert the angle (other quadrant)
		if (angleOnX < 0.0) 
			angle *= -1.0;
		// Updates the turret angle
		RotateTurret(FQuat(FRotator(0.f, actorFaceAngle + angle, 0.f)));
	}
2 Likes

I’m so happy you posted this! Thank you :smile:

1 Like

Can you explain how to make use of both the mouse and the joystick? As separate functions maybe?

I believe that the best way is to make the user choose his/her input method.
Personally, I would open a screen saying something like “Click on mouse button or press a gamepad button”.
Based on the input I would choose the strategy method.
Talking about strategy, I’ve implemented these strategies in the PawnTank class.
Here is this specific git push to my repository:

But basically, I’ve an aiming strategy, which I can select during runtime which one to use.
Each one has its own implementation for aiming and they receive a reference pointer of the APawnTank.
I choose which strategy like this:

Blockquote
PlayerAimStrategy = ConcreteAimStrategy[eAimStrategy_Mouse];

My Tick method looks like this:

Blockquote
void APawnTank::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
Rotate();
Move();
PlayerAimStrategy->Execute(this);
}

Privacy & Terms