任务:以Item类为父类,创建Weapon类,玩家在场景中可拾取该武器
第一步、角色骨骼添加武器插槽
第二步、编写Weapon类相关代码
Weapon.h代码如下:
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Item.h"
#include "Weapon.generated.h"
UCLASS()
class LEARNTEST_API AWeapon : public AItem
{
GENERATED_BODY()
public:
AWeapon();
//声明骨骼网格体组件
UPROPERTY(EditAnywhere, BlueprintReadOnly)
class USkeletalMeshComponent* WeaponMesh;
//重写重叠函数
virtual void OnOverlapBegin(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult) override;
//声明拾取函数
void Equip(class AMan* Picker);
};
Weapon.cpp代码如下:
// Fill out your copyright notice in the Description page of Project Settings.
#include "Weapon.h"
#include "Man.h"
#include "Components\StaticMeshComponent.h"
#include "Particles\ParticleSystemComponent.h"
#include "Sound\SoundCue.h"
#include "Components\SkeletalMeshComponent.h"
#include "Components\SphereComponent.h"
AWeapon::AWeapon()
{
//创建骨骼网格体组件,并将其附着在父类的StaticMesh上
WeaponMesh = CreateDefaultSubobject<USkeletalMeshComponent>(TEXT("WeaponMesh"));
WeaponMesh->SetupAttachment(StaticMesh);
}
//重写OnOverlapBegin方法
void AWeapon::OnOverlapBegin(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
//调用Item父类方法(这里注意需要将之前Item的实现中Destory()那一行删掉,因为装备武器并不需要删除自身)
Super::OnOverlapBegin(OverlappedComponent, OtherActor, OtherComp, OtherBodyIndex, bFromSweep, SweepResult);
if (OtherActor)
{
//获取重叠的角色并装备武器
AMan* Picker = Cast<AMan>(OtherActor);
if (Picker)
{
Equip(Picker);
}
}
}
void AWeapon::Equip(AMan* Picker)
{
if (Picker)
{
//关闭碰撞检测和物理模拟
WeaponMesh->SetCollisionResponseToAllChannels(ECR_Ignore);
WeaponMesh->SetSimulatePhysics(false);
//关闭粒子特效
ParticleComp->SetActive(false);
//接触碰撞重叠函数绑定
Sphere->OnComponentBeginOverlap.RemoveDynamic(this, &AItem::OnOverlapBegin);
//自身附着在角色骨骼"weapon_r"插槽
AttachToComponent(Picker->GetMesh(), FAttachmentTransformRules::SnapToTargetNotIncludingScale, "weapon_r");
}
}
第三步、以Weapon类为基类,创建蓝图类MyWeapon,在蓝图类中编辑相关的网格体和特效,就可以拖到场景中使用了。