Create a sprite from a class that inherits CCSprite - c++

I have a Balloon class (see this) that inherits from CCSprite. I have given it properties like balloonSpeed and balloonStrength. I seem to be having problems in it, though.
What I want to do is that when I make an instance of the Balloon class, I want it to do the following:
Give it a texture (a PNG file of a balloon).
Set properties like balloonSpeed and balloonStrength.
Add actions to make it move and accept touch input.
When the object is touched, I want to:
Count if # of taps = balloonStrength. if so, destroy Balloon.
I have done a simpler version of this where a Balloon object is destroyed when it is touched. I want to apply OOP and custom classes here but I can't seem to get the right way of doing it.
Thanks in advance.

then the h file should looks like below:
#include "cocos2d.h"
using namespace cocos2d;
class Balloon : public cocos2d::CCSprite, public CCTargetedTouchDelegate {
public:
float balloonSpeed;
int balloonStrength;
int numberOfTaps;
virtual void onEnter();
virtual void onExit();
virtual bool ccTouchBegan(CCTouch* touch, CCEvent* event);
virtual void ccTouchMoved(CCTouch* touch, CCEvent* event);
virtual void ccTouchEnded(CCTouch* touch, CCEvent* event);
};
and in your touch method:
bool Balloon::ccTouchBegan(CCTouch* touch, CCEvent* event){
CCPoint touchLocation = this->getParent()->convertTouchToNodeSpace(touch);
if (CCRect::CCRectContainsPoint(this->boundingBox(), touchLocation)) {
this->numberOfTaps++;
if(this->balloonStrength == this->numberOfTaps){
this->removeFromParentAndCleanup(true);
}
}
return true;
}
you can use it after you add the blueBalloon as a child of a layer or node as below:
blueBalloon->balloonSpeed = 2.0f;
blueBalloon->numberOfTaps = 0;
blueBalloon->balloonStrength = 5;

Related

C++ how to prevent import loops

I am a bit in the dark for the moment so I am trying stack overflow. My problem is that I have a classed named ‘Scene’ which will have a map of ‘GameObject’. The problem is that these GameObject need to use some function from there scene so I create a Scene* that is assigned to the main scene. The problem with this case is that I a in a loop where I import Scene which include GameObject which include Scene (and it goes on). If you think 5isnis not clear feel free to comment I will give more detail or edit this post thx.
Scene.h
class Scene
{
public:
sf::RenderWindow* window;
_Manager manager;
sf::Color backgroundColor;
std::string name;
std::map<std::string, GameObject*> gameObjects;
Scene();
Scene(std::string name);
virtual void Start() = 0;
virtual void Update() = 0;
virtual void Draw() = 0;
void _Update();
};
GameObject.h
class GameObject : public Object
{
private:
Scene* scene;
std::vector<Component*> components;
public:
Transform* transform = new Transform;
void AddComponent(Component* component);
Component* GetComponent(std::string type);
GameObject* Find();
void Instantiate(GameObject* gm, Transform* transform);
void Start();
void Update();
};
For those who got the same problem i just forgot you can do forward declaration and when you need to use the full class just import the files you need in the .cpp file of your class.

How to I use UPawnMovementComponent in Ue4 C++ instead of UFloatingPawnMovement to move a pawn?

I am having trouble figuring out how to use UPawnMovementComponent instead of UFloatingPawnMovement to move a pawn. Every time I implemented UPawnMovementComponent and hit play, the editor crashed. Here's the code.
PlayerCharacter.h
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Pawn.h"
#include "Camera/CameraComponent.h"
#include "GameFramework/SpringArmComponent.h"
#include "Components/CapsuleComponent.h"
#include "GameFramework/PawnMovementComponent.h"
#include "PlayerCharacter.generated.h"
UCLASS()
class LEARNING_API APlayerCharacter : public APawn
{
GENERATED_BODY()
public:
// Sets default values for this pawn's properties
APlayerCharacter();
UPROPERTY(EditAnywhere, Category = "Components")
UStaticMeshComponent* PlayerMesh;
UPROPERTY(EditAnywhere, Category = "Components")
UCameraComponent* Camera;
UPROPERTY(EditAnywhere, Category = "Components")
USpringArmComponent* CameraArm;
UPROPERTY(EditAnywhere, Category = "Components")
UCapsuleComponent* CapsuleComponent;
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
void MoveForward(float Amount);
void MoveRight(float Amount);
void Turn(float Amount);
void LookUp(float Amount);
PawnMovementComponent* PawnMovement;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
// Called to bind functionality to input
virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;
};
PlayerCharacter.cpp
// Fill out your copyright notice in the Description page of Project Settings.
#include "PlayerCharacter.h"
// Sets default values
APlayerCharacter::APlayerCharacter()
{
// Set this pawn to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
// Default to Player 0
AutoPossessPlayer = EAutoReceiveInput::Player0;
// Player Mesh and make it a root component
PlayerMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Player Mesh"));
RootComponent = PlayerMesh;
// Capsule Component
CapsuleComponent = CreateDefaultSubobject<UCapsuleComponent>(TEXT("Capsule Component"));
float capsule_radius = 40.f;
float capsule_height = 80.f;
CapsuleComponent->InitCapsuleSize(capsule_radius, capsule_height);
CapsuleComponent->SetupAttachment(RootComponent);
// Spring Arm Component
CameraArm = CreateDefaultSubobject<USpringArmComponent>(TEXT("Camera Arm"));
CameraArm->SetRelativeRotation(FRotator(0.f, 0.f, 0.f));
CameraArm->TargetArmLength = 500.f;
CameraArm->bEnableCameraLag = true;
CameraArm->CameraLagSpeed = 3.f;
CameraArm->SetupAttachment(RootComponent);
// Camera
Camera = CreateDefaultSubobject<UCameraComponent>(TEXT("Camera Component"));
Camera->SetupAttachment(CameraArm, USpringArmComponent::SocketName);
// Player Movement Component
PawnMovement= CreateDefaultSubobject<UPawnMovementComponent>(TEXT("Pawn Movement"));
}
// Called when the game starts or when spawned
void APlayerCharacter::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void APlayerCharacter::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
// Called to bind functionality to input
void APlayerCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
Super::SetupPlayerInputComponent(PlayerInputComponent);
PlayerInputComponent->BindAxis("MoveForward", this, &APlayerCharacter::MoveForward);
PlayerInputComponent->BindAxis("MoveRight", this, &APlayerCharacter::MoveRight);
PlayerInputComponent->BindAxis("Turn", this, &APlayerCharacter::Turn);
PlayerInputComponent->BindAxis("LookUp", this, &APlayerCharacter::LookUp);
}
void APlayerCharacter::MoveForward(float Amount)
{
PawnMovement->AddInputVector(GetActorForwardVector() * Amount);
}
void APlayerCharacter::MoveRight(float Amount)
{
PawnMovement->AddInputVector(GetActorRightVector() * Amount);
}
void APlayerCharacter::Turn(float Amount)
{
AddControllerYawInput(Amount);
}
void APlayerCharacter::LookUp(float Amount)
{
AddControllerPitchInput(Amount);
}
The reason I want to implement UPawnMovementComponent rather than UFloatingPawnMovement is because I don't want a floating pawn that moves around in the air, I want the pawn to only move on the ground. I reckon that the UPawnMovementComponent will allow me to do that. Like I said, every time I implemented, compile it, and the ran it, the editor crashed. So is there any way to implement it without the editor crashing.
Not sure if you ever solved this or not (the question is pretty old) but I believe that you can't initialize a UPawnMovementComponent directly, you need to derive your own. If you look at the class declaration you can see that the UPawnMovementComponent is marked as UCLASS(abstract). See the declaration here
Also, if you try checking that PawnMovement is not a nullptr before making any calls to it you'll prevent a crash.

Why Am I not able to debug a UE4 class inside of Visual Studio?

So I am a beginner with game programming in UE4, just starting out with c++. The code below worked perfectly before I attached a springcomponent to my mesh. This is a simple Pawn class that I created. I should also mention that once I included the spring component and tested it and it did not work, my computer shut down accidently. It give the same error repeatedly for any class I create, I have tried making a new class and applying the code.
Please see Image for the error VS 2017 gives when I try to debug
Below is the RollingStone.cpp file code.
#include "RollingStone.h"
#include "Classes/Components/InputComponent.h"
#include "Classes/GameFramework/FloatingPawnMovement.h"
#include "Classes/Camera/CameraComponent.h"
// Sets default values
ARollingStone::ARollingStone()
{
// Set this pawn to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
FloatingPawnMovement = CreateDefaultSubobject<UFloatingPawnMovement>("PawnMoevement");
StaticMesh = CreateDefaultSubobject<UStaticMeshComponent>("StaticMeshComponeent");
Camera = CreateDefaultSubobject<UCameraComponent>("CameraComponeent");
Camera->SetRelativeLocation(FVector(-500.f, 0.f, 0.f));
Camera->SetupAttachment(StaticMesh);
SetRootComponent(StaticMesh);
bUseControllerRotationYaw = true;
bUseControllerRotationPitch = true;
}
// Called when the game starts or when spawned
void ARollingStone::BeginPlay()
{
Super::BeginPlay();
}
void ARollingStone::MoveForward(float Amount)
{
FloatingPawnMovement->AddInputVector(GetActorForwardVector()* Amount);
}
void ARollingStone::MoveRight(float Amount)
{
FloatingPawnMovement->AddInputVector(GetActorRightVector()* Amount);
}
void ARollingStone::Turn(float Amount)
{
AddControllerYawInput(Amount);
}
void ARollingStone::Lookup(float Amount)
{
AddControllerPitchInput(Amount);
}
// Called every frame
void ARollingStone::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
// Called to bind functionality to input
void ARollingStone::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
Super::SetupPlayerInputComponent(PlayerInputComponent);
PlayerInputComponent->BindAxis("MoveForward", this, &ARollingStone::MoveForward);
PlayerInputComponent->BindAxis("MoveRight", this, &ARollingStone::MoveRight);
PlayerInputComponent->BindAxis("Turn", this, &ARollingStone::Turn);
PlayerInputComponent->BindAxis("LookUp", this, &ARollingStone::Lookup);
}
Below is the RollingStone.h file code:
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Pawn.h"
#include "RollingStone.generated.h"
UCLASS()
class MYPROJECT_API ARollingStone : public APawn
{
GENERATED_BODY()
public:
// Sets default values for this pawn's properties
ARollingStone();
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
void MoveForward(float Amount);
void MoveRight(float Amount);
void Turn(float Amount);
void Lookup(float Amount);
class UFloatingPawnMovement* FloatingPawnMovement;
UPROPERTY(EditAnywhere, Category = "Components")
UStaticMeshComponent* StaticMesh;
UPROPERTY(EditAnywhere, Category = "Components")
class UCameraComponent* Camera;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
// Called to bind functionality to input
virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;
};
Will appreciate you taking the time to help me. I am now very sure that the accidental shutdown caused this since its not working even after I stop using the springarmcomponent, you can see it is not there in the code and this previously working code now does not even debug.
I am using visual studio 2017 by the way!
Thank you!
Looking forward to a solution.

How To Detect If An Actor Is Hit In Unreal Engine C++?

I'm new to Unreal Engine. I'm trying to create a basic game where you control a ball and roll around, trying not to fall out of a tube and stuff. My ball looks like this:
PlayerBall.h
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Pawn.h"
#include "PlayerBall.generated.h"
UCLASS()
class ROLLINGBALL_API APlayerBall : public APawn
{
GENERATED_BODY()
public:
// Sets default values for this pawn's properties
APlayerBall();
UPROPERTY(VisibleAnywhere, Category="Mesh")
UStaticMeshComponent* Mesh;
UPROPERTY(VisibleAnywhere, Category="Camera")
class UCameraComponent* Camera;
protected:
// Called when the game starts or when spawned
void BeginPlay() override;
public:
// Called every frame
void Tick(float DeltaTime) override;
// Called to bind functionality to input
void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;
};
PlayerBall.cpp
#include "PlayerBall.h"
#include "Camera/CameraComponent.h"
// Sets default values
APlayerBall::APlayerBall() {
// Set this pawn to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
Mesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Mesh"));
const ConstructorHelpers::FObjectFinder<UStaticMesh> SphereRef(TEXT("StaticMesh'/Game/StarterContent/Shapes/Shape_Sphere.Shape_Sphere'"));
Mesh->SetStaticMesh(SphereRef.Object);
Mesh->SetSimulatePhysics(true);
Mesh->SetEnableGravity(true);
SetRootComponent(Mesh);
Camera = CreateDefaultSubobject<UCameraComponent>(TEXT("Camera"));
Camera->SetRelativeLocation(FVector(-500.0f, 0.0f, 0.0f));
Camera->SetupAttachment(RootComponent);
AutoPossessPlayer = EAutoReceiveInput::Player0;
}
// Called when the game starts or when spawned
void APlayerBall::BeginPlay() {
Super::BeginPlay();
}
// Called every frame
void APlayerBall::Tick(float DeltaTime) {
Super::Tick(DeltaTime);
}
// Called to bind functionality to input
void APlayerBall::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) {
Super::SetupPlayerInputComponent(PlayerInputComponent);
}
I also have some other obstacles and floor. However, I also want some obstacle that kills you if it hits you. I want some sort of method in the APlayerBall class that is called when it is hit, then I can check the type of actor that is hit. What can I do? What component do I use?n I looked for an hour in the documentation, but I couldn't find anything.
I tried adding the RecieveHit method, however it says that it doesn't override from a super class. I added it like this:
void ReceiveHit
(
class UPrimitiveComponent * MyComp,
AActor * Other,
class UPrimitiveComponent * OtherComp,
bool bSelfMoved,
FVector HitLocation,
FVector HitNormal,
FVector NormalImpulse,
const FHitResult & Hit
) override;
What you want to be doing is binding to the AActor::OnActorHit event with OnActorHit.AddDynamic(this, &FunctionPointer).
The RecieveHit function is internal and will be what broadcasts this event.
That would be AActor::ReceiveHit, since PlayerBall inherits from APawn which inherits from AActor.

cocos2d subclassing sprite to handle touch?

I'm new to the cocos2d(-x) world.
I'd like to detect a touch to a sprite, and tutorials/examples seem to suggest using layer to detect touch and find the approapriate sprite with bounding box.
Is subclassing sprite to allow touch detection generally a bad idea?
Note: This answer might be outdated. I answered this at 2012.
It is not a bad idea. Here is how I do it:
header file:
#include "cocos2d.h"
using namespace cocos2d;
class TouchableSprite : public cocos2d::CCSprite, public CCTargetedTouchDelegate {
public:
virtual void onEnter();
virtual void onExit();
virtual bool ccTouchBegan(CCTouch* touch, CCEvent* event);
virtual void ccTouchMoved(CCTouch* touch, CCEvent* event);
virtual void ccTouchEnded(CCTouch* touch, CCEvent* event);
};
cpp file:
#include "TouchableSprite.h"
void TouchableSprite::onEnter(){
// before 2.0:
// CCTouchDispatcher::sharedDispatcher()->addTargetedDelegate(this, 0, true);
// since 2.0:
CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(this, 0, true);
CCSprite::onEnter();
}
void TouchableSprite::onExit(){
// before 2.0:
// CCTouchDispatcher::sharedDispatcher()->removeDelegate(this);
// since 2.0:
CCDirector::sharedDirector()->getTouchDispatcher()->removeDelegate(this);
CCSprite::onExit();
}
bool TouchableSprite::ccTouchBegan(CCTouch* touch, CCEvent* event){
//do whatever you want here
return true;
}
void TouchableSprite::ccTouchMoved(CCTouch* touch, CCEvent* event){
//do what you want
}
void TouchableSprite::ccTouchEnded(CCTouch* touch, CCEvent* event){
//do your job here
}
In cocos2d-x 3.0 alpha you can try this:
auto listener = EventListenerTouchOneByOne::create();
listener->setSwallowTouches(true);
listener->onTouchBegan = [&](Touch* touch, Event* event){
if (this->getBoundingBox().containsPoint(this->convertTouchToNodeSpace(touch))) {
return true;
}
return false;
};
Director::getInstance()->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this);
it is better and much more clear to handle touches in one place. but i think, no one can bar you to do this
You do not need to subclass sprites to detect touch.
Here, Follow this LINK its a nice place to get started with Cocos2d