Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm working on a simple arcade style space shooter and I'm having some problems with my player class.
This is the code:
#include<iostream>
class player {
public:
int xPos, yPos;
void setPlayerPos(int x, int y);
int getX();
int getY();
};
void player::setPlayerPos(int x, int y) {
xPos = x;
yPos = y;
return;
}
int player::getX() {
return xPos;
}
int player::getY() {
return yPos;
}
void onGameStart() {
player Player;
Player.setPlayerPos(3,10);
}
void main() {
onGameStart();
while (gameIsRunning) {
onGameDraw();
}
}
Of course, everything starts in main() on the bottom of the code. It runs a simple onGameStart() function which is supposed to set the player's beginning coordinates.
Here is the thing. When I set the values of xPos and yPos when initializing those variables, Player.getX() and Player.getY() will always return the correct value. However, when set them using Player.setPlayerPos(x,y), then Player.getX() and Player.getY() returns junk. (Or original initialized values, if set).
I would like to know what I'm doing wrong and why Player.setPlayerPos(x,y) does not update xPos and yPos.
Try using a variable in main like this:
class player {
public:
int xPos, yPos;
void setPlayerPos(int x, int y);
int getX();
int getY();
};
void player::setPlayerPos(int x, int y) {
xPos = x;
yPos = y;
return;
}
int player::getX() {
return xPos;
}
int player::getY() {
return yPos;
}
void onGameStart(player & Player) {
Player.setPlayerPos(3,10);
}
int main() {
player Player;
onGameStart(Player);
while (gameIsRunning) {
onGameDraw(Player); // Need to know more about the implementation but it should be similiar to onGameStart.
}
}
your code seems not to be complete ...
this code seems to be not usable:
void onGameStart() {
player Player;
Player.setPlayerPos(3,10);
}
because you are changing the local variable - those player is destroyed outside of function scope. The player you are using in your code is probably some other instance - so it's x and y are not those set in your function, but some junk x and y value - because you are not initializing them in the constructor.
If you declare those player Player globaly (which is not a good practice) then your code should work (but global variables are always bad idea). Maybe try passing those player via pointer or reference to the function onGameStart
In the function onGameStart you are creating a local variable player and you set its position but then after the function ends you can no longer access it, so it is useless. Maybe you want to have a global variable player and set its position on game start? I suspect you are confusing the local variable and another one which you aren't modifying from this function and you aren't getting the results you want.
The following object: player Player; is local to your freestanding void onGameStart() function. Once that function goes out of scope the object gets destroyed. Your other object's data members remain uninitialized hence the garbage values. Your local object has nothing to do with other (main?) objects you have in a program:
int main() {
player p;
onGameStart(); // only modifies its internal object, not the p
std::cout << p.getX(); // prints garbage because xPos is uninitialized
std::cout << p.getY(); // prints garbage because yPos is uninitialized
}
And if you want the onGameStart() function to be able to modify the object one way is to pass the object by reference:
void onGameStart(player& p) {
p.setPlayerPos(3, 10);
}
Now this code prints 3 and 10:
int main() {
player p;
onGameStart(p); // now modifies the p
std::cout << p.getX(); // prints 3
std::cout << p.getY(); // prints 10
}
Maybe that's the confusion. Initialize your data members in a constructor:
class player {
public:
int xPos, yPos;
player() : xPos(0), yPos(0) {}
};
Related
I have code like this(all made for a minimal, reproducible example):
enum class gameState{
Normal,
Special};
class Piece{
public: Vector2i position;
int shape;};
class Board{
public: int array[8][8];
std::vector<Piece> f;
Board() : f(std::vector<Piece>(32)) {}; };
void promotion(int shape, gameState &state, Board &b){
state = gameState::Special;
b.array[b.f[0].position.x][b.f[0].position.y] = shape;
b.f[0].shape = shape;};
And then I try to call them in main:
int main(){
gameState state = gameState::Normal;
Board b;
promotion(1, state, b);
return 0;};
The problem is that it seems to correctly pass by reference for gameState state object, it doesn't modify Board b object, which isn't supposed to happen. How can I correctly pass Board b by reference (or a pointer)?
P.S.: Vector2f is simply a 2D vector the SFML library uses.
Actually, Board in your code is being (CORRECTLY) passed by reference to promotion function.
Are you sure it is not changed after function call?
What it prints if you do:
int main(){
gameState state = gameState::Normal;
Board b;
std::cout << b.array[b.f[0].position.x][b.f[0].position.y] <<std::endl;
promotion(1, state, b);
std::cout << b.array[b.f[0].position.x][b.f[0].position.y] <<std::endl;;
return 0;
};
I'm trying to save an Object in an 2D Vector. The vector needs to be sized at runtime. Therefore i use the resize function as mentioned in many other issues.
Her an broke down code example of my problem. So the code might not make sense but I get the same error.
Animation.h
class myPoint{
public:
int x, y;
myPoint(){}
myPoint(int x, int y) : x(x), y(y) {}
};
class AnimationFrame {
private:
std::vector<std::vector<myPoint>> sprites; //the important part
public:
void addSpritePoint(myPoint gridPos, myPoint tilePos);
...
};
class Animation {
private:
std::vector<AnimationFrame*> animationFrames;
public:
...
};
Animation.cpp
Animation::Animation() {}
int Animation::addAnimationFrame() {
AnimationFrame *newAnimationFrame = new AnimationFrame();
this->animationFrames.emplace_back(newAnimationFrame);
}
//AnimationFrame class
AnimationFrame::AnimationFrame(){
int w = 3; //just for the test
int h = 3;
this->sprites.resize(w, std::vector<myPoint>(h, myPoint(0,0)));
}
void AnimationFrame::addSpritePoint(myPoint gridPos, myPoint tilePos) {
this->sprites[gridPos.x][gridPos.y] = tilePos;
//printf(""); //breakpoint here
}
main.cpp
int main() {
Animation *a = new Animation();
a->addAnimationFrame();
a->getAnimationFrame(0).addSpritePoint(myPoint(0,0), myPoint(1,1));
a->getAnimationFrame(0).addSpritePoint(myPoint(0,1), myPoint(2,2));
a->getAnimationFrame(0).addSpritePoint(myPoint(0,2), myPoint(3,3));
}
I expect that the sprites 2D vector from my AnimationFrame class holds the values. When the first breakpoint kicks in the the Point(1,1) is in sprites(0,0) but when i now skip to the next breakpoint the values in sprites(0,0) is (0,0) again. So it resets the value. And i have no clue why.
The problem comes from the fact that Animation::getAnimationFrame() returns a copy of its internal data:
AnimationFrame Animation::getAnimationFrame(int frame) const;
So this modifies a temporary object and has no effect once the full expression has been evaluated:
a->getAnimationFrame(0).addSpritePoint(myPoint(0,0), myPoint(1,1));
The fix is simple: return by reference:
const AnimationFrame& Animation::getAnimationFrame(int frame) const
{
return *animationFrames[frame];
}
AnimationFrame& Animation::getAnimationFrame(int frame)
{
return *animationFrames[frame];
}
(yes, you need a const and a non-const version)
I'm making a simple game of catching the fruit, but I've been having troubles with the collision logic and/or using the variables from the classes.
class row
{
public:
int x,y;
void setpoint (int xi, int yi)
{
x=xi;
y=yi;
}
float DownSpeed = 5;
void down () {
y = y+DownSpeed;
if (y==1000) {
y=0;
}
}
};
class fruit:public row
{
public:
void draw()
{
setcolor(11);
circle(x,y,20);
}
};
Then I have other classes to create the catcher, like so:
class catcher
{
protected:
float moveSpeed = 5;
public:
float catchX, catchY;
void setpoint (int xi, int yi)
{
catchX=xi;
catchY=yi;
}
void MoveLeft () {
catchX = catchX - moveSpeed;}
void MoveRight () {
catchX = catchX + moveSpeed;}
};
class character:public catcher
{
public:
void draw()
{
setcolor(15);
circle(catchX,catchY,50);
}
};
How do I call the variables of both circles into creating a collision function? I'm sorry if the codes are messy and ineffective, I'm just starting out and I'm stuck. Thanks!
Since both sets of variables are in the public part of the class, you should be able to create a function independent of either class and should be able to access the variables as long as they are declared.
void CheckCollision(float x, float y, float catchX, float catchY)
{
If(y =< catchY + 5)
{
//y resets
}
}
You’d want to check if it’s within a certain x range too though. I hope this solves your problem.
Since all the functions and variables are public. return the values of x, catchX from the functions modifying them. use the draw functions after you have the modified values.
for example modify your down function like this
int down()
{
y = y+DownSpeed;
if (y==1000)
{
y=0;
}
return y;
}
Modify the other function like wise and you will end up having your x,y and catchX, catchY values. create you collison function with these values.
I'll start out with some context.
Making a simple game.
I have two classes, one called BouncingBall, and the other called ASCIIRenderer.
I have a list of instructions to follow, but some of the instructions aren't entirely clear.
First instruction was to create a pointer in BouncingBall called m_pRenderer, and have it point to a member variable in ASCIIRenderer. It wasn't specified which member variable I had to point to, and both existing member variables in there were private, so I made my own and called it Renderer.
Second instruction (the one I need help with) is when I'm writing a function for the BouncingBall class to call SetPixel using the m_pRenderer, and with three variables as parameters.
SetPixel is the name of a public function in the ASCIIRenderer class, and the instruction states I have to call it by using the pointer somehow.
Summary: I need to call a class' function from within the function of a separate class using a pointer.
Could someone explain to me what syntax I would use to accomplish this?
Based on the details you provided this is what I gathered. Assuming the BouncingBall class would get the X and Y pos and call the function foo with
the X and Y values to have the Renderer set. Also, I don't know how you will
initialize the pointer as it's not detailed above. Hope this helps.
class BouncingBall
{
public:
void foo( int posX, int posY)
{
m_pRenderer->setPixel( posX, posY);
}
private:
ASCIIRenderer* m_pRenderer;
};
The code I have included below shows an example of a class, in this case Ball, having a pointer to another class, in this case Renderer, injected and stored for later use.
The Ball class can then call public functions on the Renderer class using the 'arrow' syntax pointer->MemberFunction(arg1, arg2);
#include <iostream>
class Renderer
{
public:
/* Constructor and other functions omitted */
void SetPixel(const int x, const int y) const;
};
void Renderer::SetPixel(const int x, const int y) const
{
std::cout << "Set pixel: (" << x << ", " << y << ")" << std::endl;
}
class Ball
{
public:
Ball(const Renderer *const renderer, const int posX, const int posY);
void Render() const;
private:
const Renderer* _renderer;
int _posX;
int _posY;
};
Ball::Ball(const Renderer *const renderer, const int posX, const int posY)
: _renderer(renderer), _posX(posX), _posY(posY)
{}
void Ball::Render() const
{
_renderer->SetPixel(_posX, _posY);
}
int main()
{
const Renderer renderer;
const Ball ball(&renderer, 10, 20);
ball.Render();
return 0;
}
The output of the program is: Set pixel: (10, 20)
Lately I was working on a simple game and the game structure required me to declare many types of objects... and to make working with functions easier, I made a parent class for all of the other classes. this is a part of the entire code(simplified):
int q=500;
struct ship
{
int x,y;
bool dec=0;
};
struct enemysol : public ship
{
int life=100,y=0,x;
bool dec=0;
void declare()
{
dec=1;
x=10+rand()%(getmaxx()-20);
life=100;
y=0;
}
};
int next(ship main[]) //finding next undeclared sol
{
int i=1;
while(main[i].dec)
{
i++;
if(i==q)
return -1;
}
return i;
}
The problem is that the next function will return i even if enemysol.dec=1
this code worked when I hadn't declared ship, but the project would have been very confusing and large if I didn't declared it..
You use the wrong way to initialize the member variables of your enemysol class.
When you write:
int life=100,y=0,x;
bool dec=0;
you declare new member variables, which have the same name than the x, y and dec that you already have in ship. So everytime you use x, y or dec in your enemysol class, you don't refer to the ship variables as these are hidden.
The right way of doing it would be something like:
struct enemysol : public ship
{
int life; // define only additional member variables not already in ship
enemysol() // constructor
: y(0), dec(false), life(100) // init members
{
}
void declare()
{
dec=1;
x=10+rand()%(getmaxx()-20);
life=100;
y=0;
}
};