角色添加武器
在WeaponClass中创建骨骼网格体
//前向声明 class USkeletalMeshComponent; UPROPERTY(VisibleAnywhere, BlueprintReadWrite, Category = "Weapon") USkeletalMeshComponent* WeaponMesh;
在角色骨骼网格体中创建一个插槽Socket用于绑定武器
可以在插槽中添加武器资产用于预览:这一步是用于自己调整武器相对于插槽的旋转值
在角色类中创建一个武器类:TSubclassof<>()
UPROPERTY(EditDefaultsOnly, BlueprintReadWrite, Category = "Weapon") TSubclassOf<ASTUBaseWeapon> WeaponClass; UFUNCTION(BlueprintCallable) void SpawnWeapon();
GetWorld()->SpawnActor<>():生成actor
AttachToComponent:添加到组件,参数:要附加到的父类,旋转,插槽名
GetMesh():获取骨骼网格体
void ASTUBaseCharacter::SpawnWeapon() { if (!GetWorld()) { return; } AActor* Weapon = GetWorld()->SpawnActor<ASTUBaseWeapon>(WeaponClass); if (Weapon) { //强制转换为ASTUBaseWeapon ASTUBaseWeapon* BaseWeapon =Cast<ASTUBaseWeapon>(Weapon); //SnapToTarget会继承附加到其上的组件的转换,第二个参数表示是否开启物理模拟 FAttachmentTransformRules AttachmentRules(EAttachmentRule::SnapToTarget,false); BaseWeapon->AttachToComponent(GetMesh(), AttachmentRules, "WeaponSocket"); UE_LOG(LogTemp, Display, TEXT("Weapon %s"), *BaseWeapon->GetName()); } }
也就是蓝图的