스토리지

아이템 주워서 팔에 붙이기 본문

Unreal Engine/0. Unreal 5

아이템 주워서 팔에 붙이기

ljw4104 2023. 7. 21. 18:26

1. 결과

 

2. 과정

Weapon.cpp

void AWeapon::AttachMeshToSocket(USceneComponent* InParent, FName InSocketName)
{
	FAttachmentTransformRules TransformRules(EAttachmentRule::SnapToTarget, true);
	ItemMesh->AttachToComponent(InParent, TransformRules, InSocketName);
}

void AWeapon::Equip(USceneComponent* InParent, FName InSocketName)
{
	AttachMeshToSocket(InParent, InSocketName);
	ItemState = EItemState::EIS_Equipped;

	if (EquipSound)
	{
		UGameplayStatics::PlaySoundAtLocation(this, EquipSound, GetActorLocation());
	}

	if (Sphere)
	{
		Sphere->SetCollisionEnabled(ECollisionEnabled::NoCollision);
	}
}

SlashCharacter.cpp

void ASlashCharacter::EKeyPressed()
{
	if (AWeapon* OverlappingWeapon = Cast<AWeapon>(OverlappingItem))
	{
		OverlappingWeapon->Equip(GetMesh(), FSocketName::RightHandSocket);
		CharacterState = ECharacterState::ECS_EquippedOnHandedWeapon;
		OverlappingItem = nullptr;
		EquippedWeapon = OverlappingWeapon;
	}
	else
	{
		if (CanDisarm())
		{
			PlayEquipMontage(FName("Unequip"));
			CharacterState = ECharacterState::ECS_Unequipped;
			ActionState = EActionState::EAS_EquippingWeapon;
		}
		else if (CanArm())
		{
			PlayEquipMontage(FName("Equip"));
			CharacterState = ECharacterState::ECS_EquippedOnHandedWeapon;
			ActionState = EActionState::EAS_EquippingWeapon;
		}
	}
}
  1. E 키를 눌렀을 때 OverlappingItem 이 Weapon형으로 형변환이 가능하면 장착을 시도한다.

Item.cpp

void AItem::OnSphereOverlap(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor,
	UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
	if (ASlashCharacter *SlashCharacter = Cast<ASlashCharacter>(OtherActor))
	{
		SlashCharacter->SetOverlappingItem(this);		
	}
}

void AItem::OnSphereOvelapEnd(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor,
	UPrimitiveComponent* OtherComp, int32 OtherBodyIndex)
{
	if (ASlashCharacter *SlashCharacter = Cast<ASlashCharacter>(OtherActor))
	{
		SlashCharacter->SetOverlappingItem(nullptr);		
	}
}
  • 각각의 Item에는 USphereComponent라고 하는 구체형 컴포넌트가 있으며 해당 컴포넌트가 Overlap 여부를 판단.
  • Overlap된 Actor형 객체가 있을 때 해당 객체가 캐릭터로 형변환이 가능하다면 캐릭터에게 해당 아이템을 알림.
  • Overlap 상황이 종료되면 캐릭터에게 nullptr을 전달.
  1. Weapon 클래스에 Equip 함수를 실행 후 OverlappingItem을 null처리, 캐릭터 상태 변환 및 현재 장착된 캐릭터의 무기를 배치
  2. Weapon을 캐릭터에 배치할 때 SnapToTarget이란 옵션을 넘겨 캐릭터가 움직일때 같이 움직이도록 함.
  3. Mesh에 AttachToComponent 함수를 사용해서 해당 Mesh에 붙임. (붙일 컴포넌트 최상위, 부착 룰, 소켓 이름)

Socket

오른손에 RightHandSocket이 되어있다. 위에서 해당 함수를 호출하면 이 곳에 아이템이 장착된다.

Preview를 추가해서 각도나 위치를 조절할 수 있다.

'Unreal Engine > 0. Unreal 5' 카테고리의 다른 글

공격 시 공격받은 객체 가져오기  (0) 2023.07.21
IK Rig  (0) 2023.07.18
충돌 판정  (0) 2023.07.17
애니메이션 적용  (0) 2023.07.14
언리얼 Inverse Kinematic  (0) 2023.07.14
Comments