开火

在这篇文章中,我们准备实现开火的功能。我们再次回顾我们之前绑定的输入,如图 1 所示,我们把开火动作绑定在鼠标左键上。即我们点击鼠标左键就会触发开火。

图1 输入

因为坦克和炮塔都需要开火,所以我们把开火函数实现在基类里。

如代码清单 1 所示,我们目前还是流程调试:开火时,会在之前定义的子弹生成处,绘制一个球体。

代码清单 1 Fire
  1. void ABasePawn::Fire()
  2. {
  3.     FVector ProjectileSpawnPointLocation = ProjectileSpawnPoint->GetComponentLocation();
  4.  
  5.     DrawDebugSphere(
  6.         GetWorld(),
  7.         ProjectileSpawnPointLocation,
  8.         25.0f, 12, FColor::Red,
  9.         false, 3.0f);
  10. }

我们先验证坦克的开火功能。如代码清单 2 所示,我们使用 BindAction() 函数,将开火操作的回调函数设置为 Fire,按下时触发(IE_Pressed)。

代码清单 2 BindAction
  1. void ATank::SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent)
  2. {
  3.     Super::SetupPlayerInputComponent(PlayerInputComponent);
  4.  
  5.     PlayerInputComponent->BindAxis(TEXT("MoveForward"), this, &ATank::Move);
  6.     PlayerInputComponent->BindAxis(TEXT("Turn"), this, &ATank::Turn);
  7.  
  8.     PlayerInputComponent->BindAction(TEXT("Fire"), IE_Pressed, this, &ATank::Fire);
  9. }

最终的效果如下方视频所示,点击鼠标左键会在子弹生成处绘制球体。