C# Else confusion - if-statement

so i keep gettin an error on (else) and im not to sure what i did wrong, i cant seem to find the problem, please help, im pretty new to coding so heres the entire code i have so far
{
public float speed;
private Rigidbody2D myRigidbody;
private Vector3 change;
private Animator animator;
// Start is called before the first frame update
void Start()
{
animator = GetComponent<Animator>();
myRigidbody = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
change = Vector3.zero;
change.x = Input.GetAxisRaw("Horizontal") * Time.deltaTime * speed;
change.y = Input.GetAxisRaw("Vertical") * Time.deltaTime * speed;
if (change != Vector3.zero)
transform.Translate(new Vector3(change.x, change.y));
MoveCharacter();
UpdateAnimationAndMove();
}
void UpdateAnimationAndMove()
{
{
animator.SetFloat("moveX", change.x);
animator.SetFloat("moveY", change.y);
animator.SetBool("moving", true);
} else {
animator.SetBool("moving", false);
}
}
void MoveCharacter()
{
myRigidbody.MovePosition(transform.position + change.normalized * speed * Time.deltaTime);
}
}

You can't use else, without a corresponding if before it.
if(condition)
{
// IF condition is true, this gets executed
}
else
{
// ELSE this gets executed
}

Related

Do I need to add some kind of check before continuing when hopping to other void

I'm new(-ish) to C++, and I'm trying to learn something new every day. Today I'm trying to figure this out.
Do I have to check if Valmis == 1 so it won't continue/return before Realtest() is complete?
This is just an example.
int valmis = 0;
void test::Main()
{
//just some basic stuff
do
{
if (!strcmp())
{
//here too
float testing = 0;
printf("Test? 1=do it Else=Nothing\n");
scanf(" %f", &testing);
if (testing == 1)
{
Realtest();
//Realtest needs to be completed before continuing
if (valmis == 1) //Do I need this or does it continue after RealTest() is complete without this?
return (somethingmate = true);
}
else
{
return (somethingmate = true);
}
}
} while();
return (somethingmate = false);
}
void test::Realtest()
{
//doing something here that I need to do before continuing in main/letting somethingmate to become true
valmis = 1; //do i need this?
}

How i make function like void loop and void setup in arduino?

I want make function like void loop or void setup like arduino main function which that function can input another execution code.
unsigned long NOW;
void setup() {
}
void loop() {
void doEvery(2){ //do Every 2 second
//Put Code that Execute every 2 second
}
void doEvery(4){ //do Every 4 second
//Put Code that Execute every 4 second
}
}
How to declare/define function doEvery?
i think that function must contain
if(millis()-NOW>=EVERY){
NOW=millis();
//THE LINE CODE
}
Taking THIS as initial idea:
unsigned long previousMillis2 = 0, previousMillis100 = 0;
void setup() {
}
void loop() {
unsigned long currentMillis = millis();
//doEvery 2
if (currentMillis - previousMillis2 >= 2) {
previousMillis2 = currentMillis; //stores last execution's timestamp
//CODE EVERY 2 millis
}
//doEvery 100
if (currentMillis - previousMillis100 >= 100) {
previousMillis100 = currentMillis; //stores last execution's timestamp
//CODE EVERY 100 millis
}
}
With this, you will use millis() to ask for how many millis passed since initialization of Arduino. Then you store last time you executed your code and compare how many time passed since it.
It's not a dynamic function for defining new intervals but if you only need a pair of it, you can code it easily.
EDIT:
If you need something more dynamic, you should use anonymous functions. SEE THIS or THIS The point here is function as parameter.
I've made an animation library out of this for the WS2812 ledstrip:
https://github.com/laurijssen/ledstripanimator/blob/master/ledanim.c
The timing stuff that jabujavi describes happens in the UpdateFrame function where every animation in the list advances to the next frame after it's configured milliseconds.
class AnimList
{
Animation *first = NULL;
Adafruit_NeoPixel strip;
public:
AnimList(int nleds) : strip(nleds, 9, NEO_GRB + NEO_KHZ800)
{
strip.begin();
}
void UpdateFrame()
{
strip.clear();
Animation **anim = &first;
while (*anim)
{
if (millis() - (*anim)->last >= (*anim)->ms)
{
if (!(*anim)->UpdateFrame(strip))
{
*anim = (*anim)->next;
}
else
{
(*anim)->last = millis();
anim = &(*anim)->next;
}
}
}
}
};
Now you just call AnimList::UpdateFrame as fast as possible inside loop()
void loop() {
list->UpdateFrame();
list->Render();
if (!list->Find(&r1))
{
r1 = Rain (rand() % NUMLEDS, rand() % NUMLEDS, {BRIGHTNESS, 0, 15 }) ;
list->AddFirst(&r1);
}
}
edit
So if you want to execute code every 2 seconds you create a class which inherits from Animation and override Updateframe. Then put ms variable at the time you want to pass between frames.
Of course remove all Adafruit and animation references if you just want a task based lib.
class TaskA : public Task
{
public:
TaskA() { ms = 2000; }
bool UpdateFrame()
{
Serial.println("2 seconds passed");
return true;
}
};
TaskA t;
void setup()
{
list->AddTask(&t);
}
void loop()
{
list->UpdateTasks();
}

std::list::empty() returns true even though list is filled

I am having issues in a code having structure similar to the following minimum example. There is only one instance of MainClass. It makes new instance of Classlet on each call to its MainClass::makeclasslet()
I have multiple classlets writing to a single list buffer. After some time I need to copy/ dump the values from list buffer (FIFO).
The problem is that I am getting the following output in MainClass::clearbuffer()
>>>>>>>>>> 704 >>>>>>>>>>>>>>>>>>> Buffer size: 65363..... 1
I am unable to understand why the std::list::empty() returns true even when the buffer is locked with an atomic bool flag.
I have tried moving the call to clearbuffer() (in addval()) to the main application thread so that not each Classlet event calls clearbuffer().
I have also tried adding delay QThread::msleep(10); after setting busy = true;.
But some time after the application starts, I am getting the output shown above. Instead of popping all 65363+704 values in the list, it only popped 704 and broke the loop on list::isempty() being true (apparently).
class MainClass : public QObject {
Q_OBJECT
private:
std:: list<int> alist;
std::atomic<bool> busy;
MainClass() {
busy = false;
}
~MainClass() {
// delete all classlets
}
void makeclasslet() {
Classlet newclasslet = new Classlet();
// store the reference
}
void addval(int val) {
alist.push_back(val);
if (alist.size() > 100)
{
if (!busy)
{
clearbuffer();
}
}
}
void clearbuffer() {
if (!busy)
{
busy = true;
int i = 0;
while (!alist.empty())
{
i = i + 1;
// save alist.front() to file
alist.pop_front();
}
printf(">>>>>>>>>> %d >>>>>>>>>>> Buffer size: %d ..... %d\n", i, m_lstCSVBuffer.size(), m_lstCSVBuffer.empty());
busy = false;
}
}
}
class Classlet {
private:
Mainclass* parent;
void onsomeevent(int val) {
parent->addval(val);
}
}
I am using qt5.9 on Ubuntu 18.04. GCC/ G++ 7.5.0

Unreal engine c++ write delegate OnScreenshotCaptured

I am new to C++. I've wrote code in C# and PHP.Since I am using Unreal engine I am trying to learn C++. For my project I need to make a screenshot in-game and show it immediately so I want to get it as a texture.
I made a blueprint node which calls this function i've made:
void UMyBlueprintFunctionLibrary::TakeScreenshot()
{
FScreenshotRequest::RequestScreenshot(true);
if (GEngine)
GEngine->AddOnScreenDebugMessage(-1, 15.0f, FColor::Red, "Tried to take screenshot");
}
When I hover my mouse above RequestScreenshot I see the following pop-up:
"Screenshot can be read from memory by subscribing to the viewsport OnScreenshopCaptured delegate"
So that is what I try to do but I have no idea how I looked up this:
https://docs.unrealengine.com/latest/INT/API/Runtime/Engine/Engine/UGameViewportClient/OnScreenshotCaptured/
Can someone tell me how to implement this and how you see/know how to implement it?
I have an alternative, no delegate, but FRenderTarget::ReadPixel() to some buffer you allocated, by implementing your own UGameViewportClient (inherit it), and overriding Draw() function.
I'll show the essential codes, but not complete.
void UMyGameViewportClient::Draw(FViewport* Viewport, FCanvas* SceneCanvas)
{
Super::Draw(Viewport, SceneCanvas);
if (any_condition_you_need) {
CaptureFrame();
}
}
void UMyGameViewportClient::CaptureFrame()
{
if (!Viewport) {
return;
}
if (ViewportSize.X == 0 || ViewportSize.Y == 0) {
return;
}
ColorBuffer.Empty(); // Declare this in header as TArray<FColor>
if (!Viewport->ReadPixels(ColorBuffer, FReadSurfaceDataFlags(),
FIntRect(0, 0, ViewportSize.X, ViewportSize.Y)))
{
return;
}
SaveThumbnailImage();
}
void UMyGameViewportClient::SaveThumbnailImage()
{
IImageWrapperModule& wrappermodule = FModuleManager::LoadModuleChecked<IImageWrapperModule>(FName("ImageWrapper"));
auto wrapper_ptr = wrappermodule.CreateImageWrapper(EImageFormat::PNG);
for (int i = 0; i < ColorBuffer.Num(); i++)
{
auto ptr = &ColorBuffer[i];
auto r = ptr->R;
auto b = ptr->B;
ptr->R = b;
ptr->B = r;
ptr->A = 255;
} // not necessary, if you like bgra, just change the following function argument to ERGBFormat::BGRA
wrapper_ptr->SetRaw(&ColorBuffer[0], ColorBuffer.Num() * 4,
ViewportSize.X, ViewportSize.Y, ERGBFormat::RGBA, 8);
FFileHelper::SaveArrayToFile(wrapper_ptr->GetCompressed(), *ThumbnailFile);
}

Inherited variables are not reading correctly when using bitwise comparisons

I have a few classes set up for a game, with XMapObject as the base, and XEntity, XEnviron, and XItem inheriting it.
MapObjects have a number of flags, one of them being MAPOBJECT_SOLID. My problem is that XEntity is the only class that correctly detects MAPOBJECT_SOLID. Both Items are Environs are always considered solid by the game, regardless of the flag's state. What is important is that Environs and Item should almost never be solid.
Each class has a very basic preliminary constructor, just initializing all varibles to zero or NULL. During the CreateX() phase, Objects are linked into the map, set into a linked linked list.
Both XItem and XEnviron are a tad sloppy. They are both new, and in the middle or my debugging attempts.
Here are the relevent code samples:
XMapObject:
#define MAPOBJECT_ACTIVE 1
#define MAPOBJECT_RENDER 2
#define MAPOBJECT_SOLID 4
class XMapObject : public XObject
{
public:
Uint8 MapObjectType,Location[2],MapObjectFlags;
XMapObject *NextMapObject,*PrevMapObject;
XMapObject();
void CreateMapObject(Uint8 MapObjectType);
void SpawnMapObject(Uint8 MapObjectLocation[2]);
void RemoveMapObject();
void DeleteMapObject();
void MapObjectSetLocation(Uint8 Y,Uint8 X);
void MapObjectMapLink();
void MapObjectMapUnlink();
};
XMapObject::XMapObject()
{
MapObjectType = 0;
Location[0] = 0;
Location[1] = 1;
NextMapObject = NULL;
PrevMapObject = NULL;
}
void XMapObject::CreateMapObject(Uint8 Type)
{
MapObjectType = Type;
}
void XMapObject::SpawnMapObject(Uint8 MapObjectLocation[2])
{
if(!(MapObjectFlags & MAPOBJECT_ACTIVE)) { MapObjectFlags += MAPOBJECT_ACTIVE; }
Location[0] = MapObjectLocation[0];
Location[1] = MapObjectLocation[1];
MapObjectMapLink();
}
XEntity:
XEntity *StartEntity = NULL,*EndEntity = NULL;
class XEntity : public XMapObject
{
public:
Uint8 Health,EntityFlags;
float Speed,Time;
XEntity *NextEntity,*PrevEntity;
XItem *IventoryList;
XEntity();
void CreateEntity(Uint8 EntityType,Uint8 EntityLocation[2]);
void DeleteEntity();
void EntityLink();
void EntityUnlink();
Uint8 MoveEntity(Uint8 YOffset,Uint8 XOffset);
};
XEntity::XEntity()
{
Health = 0;
Speed = 0;
Time = 1.0;
EntityFlags = 0;
NextEntity = NULL;
PrevEntity = NULL;
IventoryList = NULL;
}
void XEntity::CreateEntity(Uint8 EntityType,Uint8 EntityLocation[2])
{
CreateMapObject(EntityType);
SpawnMapObject(EntityLocation);
if(!(MapObjectFlags & MAPOBJECT_SOLID) { MapObjectFlags += MAPOBJECT_SOLID; }
EntityFlags = ENTITY_CLIPPING;
Time = 1.0;
Speed = 1.0;
EntityLink();
}
void XEntity::EntityLink()
{
if(StartEntity == NULL)
{
StartEntity = this;
PrevEntity = NULL;
NextEntity = NULL;
}
else
{
EndEntity->NextEntity = this;
}
EndEntity = this;
}
XEnviron:
class XEnviron : public XMapObject
{
public:
Uint8 Effect,TimeOut;
void CreateEnviron(Uint8 Type,Uint8 Y,Uint8 X,Uint8 TimeOut);
};
void XEnviron::CreateEnviron(Uint8 EnvironType,Uint8 Y,Uint8 X,Uint8 TimeOut)
{
CreateMapObject(EnvironType);
Location[0] = Y;
Location[1] = X;
SpawnMapObject(Location);
XTile *Tile = GetTile(Y,X);
Tile->Environ = this;
MapObjectFlags = MAPOBJECT_ACTIVE + MAPOBJECT_SOLID;
printf("%i\n",MapObjectFlags);
}
XItem:
class XItem : public XMapObject
{
public:
void CreateItem(Uint8 Type,Uint8 Y,Uint8 X);
};
void XItem::CreateItem(Uint8 Type,Uint8 Y,Uint8 X)
{
CreateMapObject(Type);
Location[0] = Y;
Location[1] = X;
SpawnMapObject(Location);
}
And lastly, the entity move code. Only entities are capable of moving themselves.
Uint8 XEntity::MoveEntity(Uint8 YOffset,Uint8 XOffset)
{
Uint8
NewY = Location[0] + YOffset,
NewX = Location[1] + XOffset;
if((NewY >= 0 && NewY < MAPY) && (NewX >= 0 && NewX < MAPX))
{
XTile *Tile = GetTile(NewY,NewX);
if(Tile->MapList != NULL)
{
XMapObject *MapObject = Tile->MapList;
while(MapObject != NULL)
{
if(MapObject->MapObjectFlags & MAPOBJECT_SOLID)
{
printf("solid\n");
return 0;
}
MapObject = MapObject->NextMapObject;
}
}
if(Tile->Flags & TILE_SOLID && EntityFlags & ENTITY_CLIPPING)
{
return 0;
}
this->MapObjectSetLocation(NewY,NewX);
return 1;
}
return 0;
}
What is wierd, is that the bitwise operator always returns true when the MapObject is an Environ or an Item, but it works correctly for Entities. For debug I am using the printf "Solid", and also a printf containing the value of the flag for both Environs and Items.
Any help is greatly appreciated, as this is a major bug for the small game I am working on. I am also very new at Object Oriented programming, anything tips, suggestions and/or criticism are also welcome.
Your problem appears to be that you never initialize MapObjectFlags in any classes other than XEnviron so, as a basic type, it will have an unspecified value in XItem, XEntity and other XMapObject derived objects. I suggest that, as a member of XMapObject you explicitly initialize it to a known value.
As a rule, it is generally a good idea to ensure that all members of basic type are explicitly initialized in the initializer list of every constructor that you define.
e.g.
XMapObject()
: MapObjectFlags(0)
, // ... other initializers
{
// Other initializations
}
You can't (legally) be calling XEntity::MoveEntity on a MapObject or Environ because they don't have such a method. If you're using static_cast to change your object pointer into an XEntity so you can call MoveEntity on it, then you really have no guarantees about how the bit operation will work. In some implementations, things may appear to work in MoveEntity, but what's actually happening is it's interpreting the other object's memory as an XEntity. When it tries to access the offset where it believes MapObjectFlags exists, it's not actually there and always has that bit set to 1.
I figured out the problem earlier today - It didn't have any relation to OO programming, inheritance, or bitwise; it was a simple scope error.
The problem was in the fact that during my quick test to get an Environ in game, I declared the new variable inside of the control switch sequence, so the next time any control was used, the Environ would act in unpredictable ways.
switch(Event.key.keysym.sym)
{
...
case SDLK_c: { XEnviron Environ; Environ.InitEnviron(...); }
...
}