Click here to Skip to main content
15,890,579 members
Home / Discussions / C#
   

C#

 
GeneralRe: Populate a DVG from a csv file Pin
Dave Kreskowiak5-Jan-14 12:24
mveDave Kreskowiak5-Jan-14 12:24 
GeneralRe: Populate a DVG from a csv file Pin
JOHNNYDEMICHAEL8-Jan-14 0:58
JOHNNYDEMICHAEL8-Jan-14 0:58 
GeneralRe: Populate a DVG from a csv file Pin
Dave Kreskowiak8-Jan-14 2:53
mveDave Kreskowiak8-Jan-14 2:53 
GeneralRe: Populate a DVG from a csv file Pin
JOHNNYDEMICHAEL9-Jan-14 2:28
JOHNNYDEMICHAEL9-Jan-14 2:28 
GeneralRe: Populate a DVG from a csv file Pin
Dave Kreskowiak9-Jan-14 4:25
mveDave Kreskowiak9-Jan-14 4:25 
AnswerRe: Populate a DVG from a csv file Pin
OriginalGriff5-Jan-14 23:03
mveOriginalGriff5-Jan-14 23:03 
AnswerRe: Populate a DVG from a csv file Pin
Eddy Vluggen6-Jan-14 8:13
professionalEddy Vluggen6-Jan-14 8:13 
QuestionReading values from window-form to XNA Pin
larsp7775-Jan-14 0:42
larsp7775-Jan-14 0:42 
I´m working on a game using XNA and C#.

It´s a kind of two (or more) uboat-game where you place an uboat somewhere and then the opponent are going to find the uboat.

The game is maybe going to be an online-game or maybe between two computers.

I also need chat but that can be a separat program.

Anyway, right now I have a form which contains a picturebox where the actual game are.

I have a button in the form and would like to be able to affect the sprites using that button.

Right now the uboat is placed in the upper left corner. Then I want to move the uboat to destination of my choice.

However I can't affect hte uboat (enemy) with the button once the game has started.

Is it even possible?

I'm quite new to XNA and I have used this a tutorial:



Here´s my code:

Program:


C#
     using System;

namespace WindowsGame1
{
#if WINDOWS || XBOX
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main(string[] args)
        {
            Form1 form = new Form1();
            form.Show();
            Game1 game = new Game1(form.getDrawSurface());
            //game.buttonHit(400,500, true);
            game.Run();
        }
    }
#endif
}


Form1:

C#
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        Game1 game1 = new Game1();
        int counter = 1;
            
                   
        public IntPtr getDrawSurface()
        {
            return pctSurface.Handle;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            game1.buttonHit(350, 450, true);
            counter++;
            label1.Text = counter.ToString();
        }

    }
}


Game1

C#
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        private GraphicsDeviceManager graphics; // Används för att hantera grafik
        private SpriteBatch spriteBatch; // Används för att rita bilder
        private Player player; // Spelarens objekt  
        private Player player2; // Spelarens objekt
        private Enemy enemy;
        private Texture2D backgroundTexture;
        int screenWidth;
        int screenHeight;
        GraphicsDevice device;
        Rectangle textBox;
        private IntPtr drawSurface;
        int x;
        int y;
        bool isActive = false;
       
        public void buttonHit(int X, int Y, bool IsActive)
        {
            x = X;
            y = Y;
            isActive = IsActive;
        }

        public Game1(IntPtr drawSurface)
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            this.drawSurface = drawSurface;
            graphics.PreparingDeviceSettings += new EventHandler<PreparingDeviceSettingsEventArgs>(graphics_PreparingDeviceSettings);
            System.Windows.Forms.Control.FromHandle((this.Window.Handle)).VisibleChanged += new EventHandler(Game1_VisibleChanged);
        }

        public Game1()
        { 
        
        }

        

        //param name="sender"></param>
        //<param name="e"></param>
        void graphics_PreparingDeviceSettings(object sender, PreparingDeviceSettingsEventArgs e)
        {
                e.GraphicsDeviceInformation.PresentationParameters.DeviceWindowHandle =
                drawSurface;
        }
 
        /// <summary>
        /// Occurs when the original gamewindows' visibility changes and makes sure it stays invisible
        /// </summary>
        ///
        //<param name="sender"></param>
        //<param name="e"></param>
        private void Game1_VisibleChanged(object sender, EventArgs e)
        {
                if (System.Windows.Forms.Control.FromHandle((this.Window.Handle)).Visible == true)
                    System.Windows.Forms.Control.FromHandle((this.Window.Handle)).Visible = false;
        }


        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            //Istället för att initiera (skapa startvärden) här så gör vi det i Player-klassens konstruktor.
            graphics.PreferredBackBufferWidth = 1500;
            graphics.PreferredBackBufferHeight = 800;
            graphics.IsFullScreen = false;
            graphics.ApplyChanges();
            Window.Title = "Enigma";

            base.Initialize();
            
        }

      
        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            device = graphics.GraphicsDevice;
            //player = new Player(Content.Load<Texture2D>("images/player/ship"), 380, 400, 2.5f, 4.5f); //Lägg till denna. Här skapar du ditt Player-objekt.
            enemy = new Enemy(Content.Load<Texture2D>("images/enemies/uboat2_small"), 0, 0);
            player = new Player(Content.Load<Texture2D>("images/player/Ship"), 300, 400);
            if (isActive == true)
                 player2 = new Player(Content.Load<Texture2D>("images/player/Ship"), x, y);

            // TODO: use this.Content to load your game content here

            backgroundTexture = Content.Load<Texture2D>("images/Background/Atlanten3_1");
            screenWidth = device.PresentationParameters.BackBufferWidth;
            screenHeight = device.PresentationParameters.BackBufferHeight;
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();


            player.update(Window); // Anropa metoden update i player-klassen
            if (isActive == true)
                player2.update(Window); // Anropa metoden update i player-klassen
            //enemy.Update(Window); // Uppdatera fiendens position
     
            
                enemy.Update2(Window, x, y);

       

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);
            spriteBatch.Begin();
            DrawScenery();

            //spriteBatch.Draw(ship_texture, Vector2.Zero, Color.White); //Ta bort denna.
            player.Draw(spriteBatch); // Rita ut spelaren
            if (isActive == true)
                player2.Draw(spriteBatch); // Rita ut spelaren
            //if (player.Y <= 350)
              // enemy.Draw(spriteBatch);

            
            enemy.Draw(spriteBatch);


            spriteBatch.End();

            // TODO: Add your drawing code here

            base.Draw(gameTime);

        }

        private void DrawScenery()
        {
            Rectangle screenRectangle = new Rectangle(0, 0, screenWidth, screenHeight);
            spriteBatch.Draw(backgroundTexture, screenRectangle, Color.White);
        }
    }
}


GameObject-class: (base-class):


public class GameObject
{
public Texture2D texture; // Rymdskeppets textur (Från Player-klassen)
public Vector2 ship_vector; // Rymnskeppets koordinater (Från Player-klassen)

public GameObject(Texture2D texture, float X, float Y) //Delvis från Player-klassen
{
this.texture = texture;
this.ship_vector.X = X;
this.ship_vector.Y = Y;
}


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

public float X //Egenskap för att komma åt skeppets vågräta position
{
get
{
return ship_vector.X;
}
set
{
ship_vector.X = value;
}
}

public float Y //Egenskap för att komma åt skeppets lodräta position
{
get
{
return ship_vector.Y;
}
set
{
ship_vector.Y = value;
}
}

public float Width //Egenskap för att komma åt bredd på ship_texture
{
get
{
return texture.Width;
}
}

public float Height //Egenskap för att komma åt höjd på ship_texture
{
get
{
return texture.Height;
}
}
}
}



MovingObject-class:

C#
public abstract class MovingObject : GameObject
{
    public Vector2 ship_speed; // Rymdskeppets hastighet

    // =============================================================
    // MovingObject(), konstuktor för att skapa objektet  : Ärver från konstruktorn i GameObject
    // =============================================================
    //Här äver vi från konstruktor i bas-klassen. Vi måste dock ändå skapa en konstruktor för denna klassen.
    public MovingObject(Texture2D texture, float X, float Y, float speedX, float speedY) : base(texture, X, Y)
    {
           this.ship_speed.X = speedX;
           this.ship_speed.Y = speedY;
    }
}

   }


Player-class:

C#
    public class Player : MovingObject
    {
 bool isAlive = true; // För att hålla koll på om fienden lever eller inte

        public Player(Texture2D texture, float X, float Y) : base(texture, X, Y, 0.05f, 0.05f) //Sätter fart
        {
        }
     
        public void update(GameWindow window)
        {

             KeyboardState keyboardState = Keyboard.GetState();

            // Flytta rymdskeppet efter tangenttryckningar (om det inte är på
            // väg ut från kanten):
            if (ship_vector.X <= window.ClientBounds.Width - texture.Width && ship_vector.X >= 0)
                if (keyboardState.IsKeyDown(Keys.NumPad5))
                    ship_vector.X += 1;


            // Flytta på fienden:
            ship_vector.X -= ship_speed.X;
            ship_vector.Y -= ship_speed.Y;
            // Kontrollera så fienden inte åker utanför fönstret på sidorna
            if (ship_vector.X > window.ClientBounds.Width - texture.Width || ship_vector.X < 0)
                ship_speed.X *= -1; // Byt riktning på fienden
            // Gör fienden inaktiv om den åker ut där nere
            if (ship_vector.Y > window.ClientBounds.Height)
                isAlive = false;
        }
        // 
        public bool IsAlive
        {
            get { return isAlive; }
            set { isAlive = value; }
        }
    }//Here ends class



}

Enemy-class:

<pre lang="c#">

    public class Enemy : MovingObject
    {
        bool isAlive = true; 
      
        public Enemy(Texture2D texture, float X, float Y) : base(texture, X, Y, 0.05f, 0.05f)
        {
        }
        
        public void Update(GameWindow window)
        {
            // Flytta på fienden:
            ship_vector.X += ship_speed.X;
            ship_vector.Y += ship_speed.Y;
            // Kontrollera så fienden inte åker utanför fönstret på sidorna
            if (ship_vector.X > window.ClientBounds.Width - texture.Width || ship_vector.X < 0)
                ship_speed.X *= -1; // Byt riktning på fienden
            // Gör fienden inaktiv om den åker ut där nere
            if (ship_vector.Y > window.ClientBounds.Height)
                isAlive = false;
        }

        public void Update2(GameWindow window, int x, int y)
        {
            ship_vector.X = x;
            ship_vector.Y = y;   
        }
        // =======================================================================
        // Egenskaper för Enemy
        // =======================================================================
        public bool IsAlive
        {
            get { return isAlive; }
            set { isAlive = value; }
        }
    }
}

AnswerRe: Reading values from window-form to XNA Pin
Ron Beyer5-Jan-14 17:52
professionalRon Beyer5-Jan-14 17:52 
GeneralRe: Reading values from window-form to XNA Pin
larsp7775-Jan-14 22:09
larsp7775-Jan-14 22:09 
GeneralRe: Reading values from window-form to XNA Pin
Ron Beyer6-Jan-14 7:44
professionalRon Beyer6-Jan-14 7:44 
GeneralRe: Reading values from window-form to XNA Pin
larsp7776-Jan-14 8:24
larsp7776-Jan-14 8:24 
GeneralRe: Reading values from window-form to XNA Pin
larsp7773-Feb-14 22:00
larsp7773-Feb-14 22:00 
Questionhow i can auto searching devices and sending file with bluetooth using 32feet ,C#,WPf Pin
h.k_net4-Jan-14 21:32
h.k_net4-Jan-14 21:32 
AnswerRe: how i can auto searching devices and sending file with bluetooth using 32feet ,C#,WPf Pin
Kornfeld Eliyahu Peter4-Jan-14 22:29
professionalKornfeld Eliyahu Peter4-Jan-14 22:29 
QuestionCreating C# TCP listener windows Service Pin
Tobben_4-Jan-14 11:47
Tobben_4-Jan-14 11:47 
AnswerRe: Creating C# TCP listener windows Service PinPopular
Ron Beyer4-Jan-14 12:00
professionalRon Beyer4-Jan-14 12:00 
QuestionGetting Thread Exception: while using System.Timer Class Pin
Member 99612394-Jan-14 7:16
Member 99612394-Jan-14 7:16 
AnswerRe: Getting Thread Exception: while using System.Timer Class Pin
Pete O'Hanlon4-Jan-14 8:15
mvePete O'Hanlon4-Jan-14 8:15 
AnswerRe: Getting Thread Exception: while using System.Timer Class Pin
Dave Kreskowiak4-Jan-14 10:20
mveDave Kreskowiak4-Jan-14 10:20 
AnswerRe: Getting Thread Exception: while using System.Timer Class Pin
Brite Varghese9-Jan-14 6:22
Brite Varghese9-Jan-14 6:22 
AnswerRe: Getting Thread Exception: while using System.Timer Class Pin
Member 99612399-Jan-14 17:47
Member 99612399-Jan-14 17:47 
QuestionC# datagridview navigator Pin
Member 78188924-Jan-14 3:58
Member 78188924-Jan-14 3:58 
AnswerRe: C# datagridview navigator Pin
Alan N4-Jan-14 4:20
Alan N4-Jan-14 4:20 
Questionabout Sign unsigned drivers Pin
delphix53-Jan-14 8:43
delphix53-Jan-14 8:43 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.