Custom Component, Unreal Engine里定制组件

if you want to do every tick to any Actor, you'd better write your own Component. 
the probable  problems you may went through:

1. TickComponent not called at all.
solution:  You can set the ticking properties of a component through its PrimaryComponentTick property. Try adding the following to your component's constructor:
PrimaryComponentTick.bCanEverTick = true;

2. TickComponent called only Once.
Solution:  As it turns out. C++ components are not active by default. Activating the component caused TickComponent to be called more than once. Tye adding the following to your component's constructor:
bAutoActivate = true;

3. You can not fine your custom Component in the Add Components List
I think you may be missing sth like "..,meta = (BlueprintSpawnableComponent)" just before function declaration.

Get ActorLocation and Rotation should be written as:
this->GetOwner()->GetLocation();
this->GetOwner()->SetLocation(...);
this->GetOwner()->GetRotation();
this->GetOwner()->SetRotation(...);

Sample:
.h
#pragma once 
#include "FaceToMainCharacterComp.generated.h" 
UCLASS(ClassGroup = FaceTo,meta = (BlueprintSpawnableComponent)) 
class UFaceToMainCharacterComp : public UActorComponent 
{ 
     GENERATED_UCLASS_BODY() 
protected: 
     virtual void TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction); 
};

.cpp
#include "MyThirdPersonCode.h"   //change it to YourOwnGame.h
#include "FaceToMainCharacterComp.h"

UFaceToMainCharacterComp::UFaceToMainCharacterComp(class FPostConstructInitializeProperties const &PCIP)
: Super(PCIP)
{
PrimaryComponentTick.bCanEverTick = true;
bAutoActivate = true;
}

void UFaceToMainCharacterComp::TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction)
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
ACharacter* player = UGameplayStatics::GetPlayerCharacter(this, 0);
FVector playerLoc = player->K2_GetActorLocation();
FVector actorLoc = this->GetOwner()->GetActorLocation();
FVector offDir = playerLoc - actorLoc;
offDir *= FVector(1.0, 1.0, 0.0);
offDir.Normalize();
FRotator rot = offDir.Rotation();

this->GetOwner()->SetActorRotation(rot);

FVector tmp;
float length = 0.0;
FVector distDir = playerLoc - actorLoc;
distDir.ToDirectionAndLength(tmp, length);
distDir.Normalize();
if (length > 100.0)
{
     this->GetOwner()->SetActorLocation(actorLoc + distDir);
}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值