Unable to pass the string variable to Sprite in cocos2dx - c++

I'm having problem with the strings in cocos2dx & C++. I want to pass the variable background to Sprite::create(background) however, I get an error. If it was in java the following code will work, but since I'm not used to C++ it may be different. Plus, if it was a int how will I pass it ? How will I be able to solve this? Some tips or samples will be great! I will love to hear from you!
void GameLayer::initBackground()
{
UserDefault *_userDef = UserDefault::getInstance();
//int型
auto _int =_userDef->getIntegerForKey("back");
auto string background = "Background1.png";
if (_int == 0) {
background = "Background2.png";
}
auto bgForCharacter = Sprite::create(background);
bgForCharacter->setAnchorPoint(Point(0, 1));
bgForCharacter->setPosition(Point(0, WINSIZE.height));
addChild(bgForCharacter, ZOrder::BgForCharacter);
auto bgForPuzzle = Sprite::create("Background2.png");
bgForPuzzle->setAnchorPoint(Point::ZERO);
bgForPuzzle->setPosition(Point::ZERO);
addChild(bgForPuzzle, ZOrder::BgForPuzzle);
}

auto userDefault=UserDefault::getInstance();
int value=userDefault->getIntegerForKey("back"); //find value for back if exist then it return that value else return 0
auto sprite = Sprite::create(value==0?"Background2.png":"Background1.png");
sprite->setPosition(100, 100);
this->addChild(sprite, 0);
When you want to change your background just put any value rather than 0
UserDefault::getInstance()->setIntegerForKey("back", 1);

Related

cant get the correct value while using GEngine->AddOnScreenDebugMessage() Unreal engine 2.27

I am trying to add a lean function to my c++ project, after calculating the YawDelta I want to displayed to my screen using the GEngine->AddOnScreenDebugMessage()
the problem it's always 0 in the viewport screen when pressing play
here is my c++ code of the Lean function which is called in UpdateAnimationProperties (Tick)
void UShooterAnimInstance::Lean(float DeltaTime)
{
if (ShooterCharacter == nullptr) return;
CharacterYawLastFrame = CharacterYaw;
CharacterYaw = ShooterCharacter->GetActorRotation().Yaw;
const float Target{ (CharacterYaw - CharacterYawLastFrame) / DeltaTime };
const float Interp{ FMath::FInterpTo(YawDelta, Target, DeltaTime, 6.f) };
YawDelta = FMath::Clamp(Interp, -90.f, 90.f);
if (GEngine) GEngine->AddOnScreenDebugMessage(5,
-1,
FColor::Cyan,
FString::Printf(TEXT("YawDelta : %f"),
YawDelta));
}
PS: if I use UE_LOG, the output log shows the variable 2 times, one with the correct value and the other one is always 0
Please help
Have you tried calling the AddOnScreenDebugMessage with YawDelta in the AnimInstance's NativeUpdateAnimation ? Try it there after Super::NativeUpdateAnimation(DeltaSeconds)and see what result you get.

Camera Shake Not Activating Unreal C++

I am trying to set a camera shake for my character in Unreal C++.
Currently, I declare the instance variable in my header class.
Using log outputs, the code is reaching the right location in the OnFire() function, meaning none of the pointers are null. But the camera shake doesn't work.
UPROPERTY(EditAnywhere)
UCameraShake* CShake;
// And here is how I call it
void AZombieCharacter::BeginPlay(){
SetUpCameraShake();
}
...
void AZombieCharacter::OnFire() {
...
auto CTRLR = UGameplayStatics::GetPlayerController(GetWorld(), 0);
if (CTRLR) {
auto CM = CTRLR->PlayerCameraManager;
if (CM) {
CM->PlayCameraShake(CShake->GetClass(), 1.0f);
}
else {
UE_LOG(LogTemp, Warning, TEXT("CANNOT FIND CM"));
}
}
else {
UE_LOG(LogTemp, Warning, TEXT("CANNOT FIND CTRLR"));
}
}
...
void AZombieCharacter::SetUpCameraShake() {
CShake = UCameraShake::StaticClass()->GetDefaultObject<UCameraShake>();
CShake->OscillationDuration = 4.f;
CShake->OscillationBlendInTime = 0.5f;
CShake->OscillationBlendOutTime = 0.5f;
CShake->RotOscillation.Pitch.Amplitude = FMath::RandRange(5.0f, 10.0f);
CShake->RotOscillation.Pitch.Frequency = FMath::RandRange(25.0f, 35.0f);
CShake->RotOscillation.Yaw.Amplitude = FMath::RandRange(5.0f, 10.0f);
CShake->RotOscillation.Yaw.Frequency = FMath::RandRange(25.0f, 35.0f);
}
Thanks.
Play Camera Shake Accepts an UClass / TSubClassOf<UCameraShake> knowing that would expect us to think that this function would eventually construct a new object and ignore the default object options.
I would recommend to subclass the UCameraShake class and use TSubClassOf to store your class type instead of the pointer like CShake. As it may be garbage collected without you knowing who knows?
Here is a C++ tutorial on UCameraShake's.
https://unrealcpp.com/camera-shake/
The reason your shake is not playing is likely having no actual parameters passed to the shake. Only the default ones despite your try to set the default values, it does not seem to take it into account for newly created objects.

SDL1 -> SDL2 resolution list building with a custom screen mode class

My engine was recently converted to run with SDL2 for input, and video. However, I am having a hard time getting the resolution mode list building working correctly. I did study the Migration Guide for SDL2, as well as heavily research links -- I am not sure how to go about it, several failed attempts later.
So, for starters, I have a file, called i_video.cc, that handles SDL2 video code. 99% of the engine runs in OpenGL, so SDL is only there to initialize the window and set any variables.
So, here was the old way of grabbing resolution into our screen mode class. For reference, the screen mode class is defined in r_modes.cc.
With that said, here is the old SDL1-based code that builds the screen mode list, that I cannot, for the LIFE of me, get running under SDL2. This code starts at line 190 in i_video.cc. For reference, the old code:
// -DS- 2005/06/27 Detect SDL Resolutions
const SDL_VideoInfo *info = SDL_GetVideoInfo();
SDL_Rect **modes = SDL_ListModes(info->vfmt,
SDL_OPENGL | SDL_DOUBLEBUF | SDL_FULLSCREEN);
if (modes && modes != (SDL_Rect **)-1)
{
for (; *modes; modes++)
{
scrmode_c test_mode;
test_mode.width = (*modes)->w;
test_mode.height = (*modes)->h;
test_mode.depth = info->vfmt->BitsPerPixel; // HMMMM ???
test_mode.full = true;
if ((test_mode.width & 15) != 0)
continue;
if (test_mode.depth == 15 || test_mode.depth == 16 ||
test_mode.depth == 24 || test_mode.depth == 32)
{
R_AddResolution(&test_mode);
}
}
}
// -ACB- 2000/03/16 Test for possible windowed resolutions
for (int full = 0; full <= 1; full++)
{
for (int depth = 16; depth <= 32; depth = depth + 16)
{
for (int i = 0; possible_modes[i].w != -1; i++)
{
scrmode_c mode;
mode.width = possible_modes[i].w;
mode.height = possible_modes[i].h;
mode.depth = depth;
mode.full = full;
int got_depth = SDL_VideoModeOK(mode.width, mode.height,
mode.depth, SDL_OPENGL | SDL_DOUBLEBUF |
(mode.full ? SDL_FULLSCREEN : 0));
if (R_DepthIsEquivalent(got_depth, mode.depth))
{
R_AddResolution(&mode);
}
}
}
}
It is commented out, and you can see the SDL2 code above it that sets SDL_CreateWindow. The video is just fine in-game, but without resolution building, we cannot get screen-resolution changes without passing command-line arguments first before the program loads. I wish they left SOME kind of compatibility layer, because it seems SDL2 has a slight learning curve over the way I've always handled this under SDL1.
I know that ListModes and VideoInfo no longer exist, and I've tried replacing them with equivalent SDL2 functions, such as GetDisplayModes, but the code just doesn't work correctly. I am not sure how I'm supposed to do this, or if r_modes.cc just needs to be completely refactored, but all I need it to do is grab a list of video modes to populate my scrmode_c class (in r_modes.cc).
When I try to replace everything with SDL2, I get an invalid cast from SDL_Rect* to SDL_Rect**, so maybe I am just doing this all wrong. Several months I've spent trying to get it working, and it just doesn't want to. I don't care much about setting bits-per-pixel, as modern machines can just default to 24 now and we don't need any reason to set it to 16 or 8 anymore (nowadays, everyone has an OpenGL card that can go above 16-bit BPP) ;)
Any advice, help...anything at this point would be greatly appreciated =)
Thank you!
-Coraline
Use a combination of SDL_GetNumDisplayModes and SDL_GetDisplayMode, then push these back into a vector of SDL_DisplayMode.
std::vector<SDL_DisplayMode> mResolutions;
int display_count = SDL_GetNumVideoDisplays();
SDL_Log("Number of displays: %i", display_count);
for (int display_index = 0; display_index <= display_count; display_index++)
{
SDL_Log("Display %i:", display_index);
int modes_count = SDL_GetNumDisplayModes(display_index);
for (int mode_index = 0; mode_index <= modes_count; mode_index++)
{
SDL_DisplayMode mode = { SDL_PIXELFORMAT_UNKNOWN, 0, 0, 0, 0 };
if (SDL_GetDisplayMode(display_index, mode_index, &mode) == 0)
{
SDL_Log(" %i bpp\t%i x %i # %iHz",
SDL_BITSPERPIXEL(mode.format), mode.w, mode.h, mode.refresh_rate);
mResolutions.push_back(mode);
}
}
}

Don't understand these C++ box2d Errors

I've trying to get this C++ method to work in my iOS game.
-(b2Vec2) RayCheckWithInput:p1 andX:p2
{
b2RayCastInput input;
input.p1 = p1;
input.p2 = p2;
input.maxFraction = 1;
//check every fixture of every body to find closest
float closestFraction = 1; //start with end of line as p2
b2Vec2 intersectionNormal(0,0);
for (b2Body* b = self.world.world->GetBodyList(); b; b = b->GetNext()) {
for (b2Fixture* f = b->GetFixtureList(); f; f = f->GetNext()) {
b2RayCastOutput output;
if ( ! f->RayCast( &output, input ) )
continue;
if ( output.fraction < closestFraction ) {
closestFraction = output.fraction;
intersectionNormal = output.normal;
}
}
}
b2Vec2 intersectionPoint = p1 + closestFraction * (p2 - p1);
return intersectionPoint;
}
I know a fair bit about obj-c, but not C++. Here's a screen shot of the errors for that method it's showing.
Any help appreciated (in Chrome you can do right click and open image in new tab to see it better)
You need to be more explicit with the variables passed into the Objective-C function. You are passing without a type so it is not able to infer that it is actually a C++ type rather than an Objective-C type.
Try something like:
-(b2Vec2) RayCheckWithInput: (CPPTye*)p1 andX: (CPPTye*)p2
Edit: a quick check of the box2d docs says you need something like this:
-(b2Vec2) RayCheckWithInput: (b2Vec2)p1 andX: (b2Vec2)p2
Edit 2: Also worth noting that the Raycast function takes a third parameter childIndex as described in the docs.

Keyframing in 3DS MAX 2014 SDK c++

I want to ask you guys to help me with creating keyframes in Max SDK C++.
What I've done:
Created a Controller Plugin
Inside the getValue function I've done my translations via code.
I also wrote the setValue function.
Which I think manages keyframes and stores the controllers position in a given time in a given keyframe. In this way I achieved to be able to set keys manually, but I really would like, to work with the Auto Key turned on in Max.
On the other hand, I can't see the freshly added keys values. So please help me, how could I add keyframes?
Many Thanks:
Banderas
void maxProject3::GetValue(TimeValue t, void *ptr, Interval &valid, GetSetMethod method)
{
Point3 p3OurAbsValue(0, 0, 0);
tomb[0]=0;
//These positions stores my data they are globals
XPosition += (accX);
YPosition += (accY);
ZPosition += (accZ);
p3OurAbsValue.x = XPosition;
p3OurAbsValue.y = YPosition;
p3OurAbsValue.z = ZPosition;
valid.Set(t,t+1); //This answer is only valid at the calling time.
MatrixCtrl->GetValue(t, &p3OurAbsValue.y, valid, CTRL_RELATIVE);
if (method == CTRL_ABSOLUTE)
{
Point3* p3InVal = (Point3*)ptr;
*p3InVal = p3OurAbsValue;
}
else // CTRL_RELATIVE
{
//We do our translations on a Matrix
Matrix3* m3InVal = (Matrix3*)ptr;
//m3InVal->PreTranslate(p3OurAbsValue);
m3InVal->PreRotateX(rotX);
m3InVal->PreRotateY(rotY);
m3InVal->PreRotateZ(rotZ);
}
}
int maxProject3::NumSubs() {
return 1;
}
Animatable* maxProject3::SubAnim(int n) {
return MatrixCtrl;
}
void maxProject3::SetValue(TimeValue t, void *ptr, int commit, GetSetMethod method)
{
Matrix3* m3InVal = (Matrix3*)ptr;
MatrixCtrl->AddNewKey(t, ADDKEY_SELECT);
MatrixCtrl->SetValue(t, &m3InVal, commit, CTRL_RELATIVE);
}
To turn on the Auto key mode try using AnimateOn() before your transformation. Also add AnimateOff() to turn off the auto key mode in the end.
I did it in one of my project to create material id animation using auto key mode.
/** Auto key on*/
AnimateOn();
/** Creating material id animation */
for(int mtl_id = 1; mtl_id <= num_sub_mtl; ++mtl_id, time += time_step)
{
mtl_modifier->GetParamBlock()->SetValue(MATMOD_MATID,time,mtl_id);
}
/** Auto key off*/
AnimateOff();
Also as a suggestion, use the max script listener to know whats happening when the animation is created using 3ds Max GUI. This will help you to recreate the animation using Max SDK.