Having a problem to get values from different methods which contain different classes

Started by
14 comments, last by Lactose 8 years, 5 months ago

Okay the title might be wtf, so here is what my problem is:

I have created 2 classes, one is bullet.cs and one is enemy.cs, then in Game1.cs I created a bullet method(s) first to make a player shoot,

It wrked very well, and then I created enemy method to spawn enemys, which works just the way I want it.

Now what I am trying to do is to decrement enemy.Health (enemy is an element of List enemys) every time the bullet(bullet is an element of List bullets) hits it,

but I cant acces position values becouse they are in their own methods:

Enemy method:


public void Enemyss()
        {
            Enemy enemy = new Enemy(Content.Load<Texture2D>("Enemy"), new Vector2(e_x, 100), new int(), new int());
            enemy.Health = 10;            

            if (enemys.Count() < 8)
            {
                enemys.Add(enemy);
                e_x += 100;
            }
         
           
            
        }

One of the bullet methods:


 public void Shoot()
        {
            Bullet newBullet = new Bullet(Content.Load<Texture2D>("b"));
            newBullet.velocity = 10f;
            newBullet.position.Y = ((pla.pla_pos.Y+20) + newBullet.velocity);
            newBullet.position.X = pla.pla_pos.X + 28;
            
            if (bullets.Count() < 30)
            {
                bullets.Add(newBullet);
            }           
            

        }

So now I want to do something like


if(newbullet.positon.X == enemy.ePosition.X && newbullet.positon.Y == enemy.ePosition.Y)
{
bla
bla
bla

}

But as you might now I cant acces bullet position or enemy position out of their methods, so what should I do?

Advertisement

Hello,

You may want to change your creation methods to something like below. By moving the "new" inside the "if", you only create new bullets if you really have room for it.


public void Shoot()
{
    if (bullets.Count() < 30)
    {
        Bullet newBullet = new Bullet(Content.Load<Texture2D>("b"));
        newBullet.velocity = 10f;
        newBullet.position.Y = ((pla.pla_pos.Y+20) + newBullet.velocity);
        newBullet.position.X = pla.pla_pos.X + 28;

        bullets.Add(newBullet);
    }
}

As for your question,

The point of object-oriented programming is that you should let the object that is most suitable handle the thing you want.

In this case, I think an enemy is best suited for deciding if it is hit.

So rather than asking at a global level "if(newbullet.positon.X == enemy.ePosition.X && newbullet.positon.Y == enemy.ePosition.Y)", you ask

"if (enemy.isHitBy(newbullet)) { ... }"

Inside "enemy" you add a method "boolean isHitBy(Buillet b)" (Edit: "boolean" may be "bool", I am not very much at home with C#) that returns true if the bullet is near enough the enemy (being exactly at the same point is probably not enough, but you should try it). While this solves the enemy position (since an enemy can access its own position), you still cannot access the bullet position.

You solve this by adding a "Position getPosition() { return position; }" method to the bullet, so its environment can query the position of a bullet.

Okay in Bullet.cs I putted this code:


public Vector2 getPositionB()
        {
            return position;
        }

and in Enemy.cs I putted this code:


public bool isHit(Bullet b, Enemy e)
        {            
            if (b.position.X == e.ePosition.X && b.position.Y == e.ePosition.Y)
            {
                return true;
            }
            else return false;
        }

....
....
....
....
....

public Vector2 getPositionB()
        {
            return ePosition;
        }

but now I made an error that says that I cant assign 'isHit' becouse its a method group

(


public Enemy(Texture2D newET, Vector2 newEP, int newHealth, bool isHit_)
        {
            eTexture = newET;
            ePosition = newEP;
            Health = newHealth;
            isHit = isHit_;
        } 

)

Why are you passing an "isHit_" bool into the constructor? What would that be for? Just remove it.


public Enemy(Texture2D newET, Vector2 newEP, int newHealth)
        {
            eTexture = newET;
            ePosition = newEP;
            Health = newHealth;
        } 

Why are you passing an "isHit_" bool into the constructor? What would that be for? Just remove it.


public Enemy(Texture2D newET, Vector2 newEP, int newHealth)
        {
            eTexture = newET;
            ePosition = newEP;
            Health = newHealth;
        } 

EDIT: I cant use enemy.isHit in game1.cs, it says cannot convert method blabla to non delegate type bool

EDIT2: I have to check for value of bool in Game1.cs becouse I need to remove enemy from list enemys if isHit == true

You're going to have to show more of your actual code. Also, when reporting error messages, replacing parts with "blabla" doesn't help us help you. Those "blabla" bits are important.

Well so here is my enemy class


class Enemy
    {
        public Texture2D eTexture;
        public Vector2 ePosition;
        public int Health;

        public bool isHit(Bullet b, Enemy e, bool value)
        {
            if (b.position.X == e.ePosition.X && b.position.Y == e.ePosition.Y)
            {
                value = true;
                return value;
            }
            else
            {
                value = false;
                return value;
            }
            
        }
        
        public Enemy(Texture2D newET, Vector2 newEP, int newHealth)
        {
            eTexture = newET;
            ePosition = newEP;
            Health = newHealth;
            
        }
        
        public Vector2 getPositionB()
        {
            return ePosition;
        }
      

        public void Draw(SpriteBatch spriteBatch)
        {
            spriteBatch.Draw(eTexture, ePosition, Color.White);
        }

And here is Game1.cs class


public class Game1 : Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        // Player
        Player pla;

        // Enemy
        List<Enemy> enemys = new List<Enemy>();
        int e_x;

        // Bullets
        List<Bullet> bullets = new List<Bullet>();
        KeyboardState pastKey;

        // Level       


        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            graphics.PreferredBackBufferHeight = 800;
            graphics.PreferredBackBufferWidth = 900;
        }

        
        protected override void Initialize()
        {
            
            base.Initialize();
        }

        protected override void LoadContent()
        {
            spriteBatch = new SpriteBatch(GraphicsDevice);
            pla = new Player(Content.Load<Texture2D>("pla"), new Vector2(400, 700));
            
        }

       
        protected override void UnloadContent()
        {
           
        }

        // ----------------- UPDATE ------------------ UPDATE ------------------ UPDATE--------------
        protected override void Update(GameTime gameTime)
        {

            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
                Exit();

            if (Keyboard.GetState().IsKeyDown(Keys.Space) && pastKey.IsKeyUp(Keys.Space))
            {
                Shoot();
            }

            pastKey = Keyboard.GetState();

            // Level Check ----- Level Check ----- Level Check ----- Level Check ----- Level Check -----
            
            Enemyss();

            // Updates
            UpdateBullet();
            pla.Update();                 
            base.Update(gameTime);
        }


        public void UpdateBullet()
        {
            foreach (Bullet bullet in bullets)
            {
                bullet.position.Y -= bullet.velocity;
                if (Vector2.Distance(bullet.position, pla.pla_pos) > 800)
                { bullet.isVisible = false; }
            }
            for (int i = 0; i < bullets.Count; i++)
                {

                if (!bullets[i].isVisible)
                {   bullets.RemoveAt(i);
                    i--; }

                }
        }

        public void Enemyss()
        {
            Enemy enemy = new Enemy(Content.Load<Texture2D>("Enemy"), new Vector2(e_x, 100), new int());            
            enemy.Health = 10;

            if (enemys.Count() < 8)
            {
                enemys.Add(enemy);
                e_x += 100;
            }

            
            
            
        }        
        
        
        // ------------- Shoot ----------------------------------------------------- Shoot
        public void Shoot()
        {
            Bullet newBullet = new Bullet(Content.Load<Texture2D>("b"));
            newBullet.velocity = 10f;
            newBullet.position.Y = ((pla.pla_pos.Y+20) + newBullet.velocity);
            newBullet.position.X = pla.pla_pos.X + 28;
            
            if (bullets.Count() < 30)
            {
                bullets.Add(newBullet);
            }           
            
            
        }
        
        
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.OldLace);

            spriteBatch.Begin();
            // Player
            pla.Draw(spriteBatch);

            // Bullets
            foreach (Bullet bullet in bullets)
            {
                bullet.Draw(spriteBatch);
            }
            // Enemys draw
            foreach (Enemy enemy in enemys)
            {
                enemy.Draw(spriteBatch);
            }


            spriteBatch.End();
                    
            base.Draw(gameTime);
        }
    }

and here is Bullet.cs


class Bullet
    {
        public Texture2D texture;
        public Vector2 position;
        public float velocity;
        public bool isVisible;

        public Bullet(Texture2D newTexture)
        {
            texture = newTexture;
            isVisible = true;
        }

        public void Draw(SpriteBatch spriteBatch)
        {
            spriteBatch.Draw(texture, position, Color.White);
        }

        public Vector2 getPositionB()
        {
            return position;
        }
       
    }

So again, I want to get true or false for enemy.isHit but I cant cause error says I cant use it like that cause its a method, so I then tried somethng like value = true(false); return value; and then to use bool value that too didnt work so well

The code you've posted doesn't show where you call isHit().

Also, you created a method in Bullet to get the bullet's position, but you're not calling it in Enemy's isHit() method. You're still trying to directly access the bullet's x and y members.

Finally, why are you including an Enemy object as a parameter to Enemy's isHit() method? The enemy object already knows which enemy it is and has direct access to its own position.

I think you need to step back and do some basic C# tutorials before proceeding further. You're just going to frustrate yourself.

I think you need to step back and do some basic C# tutorials before proceeding further. You're just going to frustrate yourself.

This ^

This topic is closed to new replies.

Advertisement