Ir para conteúdo

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Pedroalves

[Resolvido] Iniciando em Criação de jogos

Recommended Posts

Depende, você tem alguma noção de como fazer um jogo? Com RPG Maker, já fez algo do tipo, Game Maker?

 

Tem algum conhecimento em programação, lógica?

 

Caso não sabe nada de programação, você tem uma longaaaaaa caminhada aí rsrs

 

Primeiramente aconselho um bom entendimento de lógica, depois seguir para uma linguagem de programação estruturada para entender na prática os funcionamentos básicos, if, loops, variáveis e dominar esses conceitos, então partir p/ uma linguagem POO já podendo ser voltado a programação de jogos: Actionscript 3.0, C++, Java, C#.

 

Defina também o estilo de jogo que quer desenvolver, ou focar seus estudos inicialmente, cada estilo de jogo tem uma lógica diferente do outro. A câmera (1ª pessoa, top down (vista de cima), ou aerial side (vista de lado) e os gráficos (2D ou 3D) também influenciam no caminho que deve seguir.

 

Não existe a melhor linguagem, e nem a mais fácil, existe a que você mais se identifica.

 

Espero ter ajudado :)

Compartilhar este post


Link para o post
Compartilhar em outros sites

tenho algumas bases logicas

pois eu cheguei a programar em java, php, sql mas coisas muito simples

 

estou a usar o XNAGAME da Microsoft

não estou a conseguir passar o código de gamepade para teclado e tb possa usar o rato

segue-se o código

#region File Description
//-----------------------------------------------------------------------------
// Game1.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace GoingBeyond1_Tutorial
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

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

        /// <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()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
        }


        // Set the 3D model to draw.
        Model myModel;

        // The aspect ratio determines how to scale 3d to 2d projection.
        float aspectRatio;

        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            myModel = Content.Load<Model>("Models\\p1_wedge");
            aspectRatio = graphics.GraphicsDevice.Viewport.AspectRatio;
        }
        
        /// <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
        }
        Vector3 modelVelocity = Vector3.Zero;
       
        protected void UpdateInput()
{
    // Get the game pad state.
    GamePadState currentState = GamePad.GetState(PlayerIndex.One);
    if (currentState.IsConnected)
    {
        // Rotate the model using the left thumbstick, and scale it down.
        modelRotation -= currentState.ThumbSticks.Left.X * 0.10f;

        // Create some velocity if the right trigger is down.
        Vector3 modelVelocityAdd = Vector3.Zero;

        // Find out what direction we should be thrusting, using rotation.
        modelVelocityAdd.X = -(float)Math.Sin(modelRotation);
        modelVelocityAdd.Z = -(float)Math.Cos(modelRotation);

        // Now scale our direction by how hard the trigger is down.
        modelVelocityAdd *= currentState.Triggers.Right;

        // Finally, add this vector to our velocity.
        modelVelocity += modelVelocityAdd;

        GamePad.SetVibration(PlayerIndex.One, currentState.Triggers.Right,
            currentState.Triggers.Right);


        // In case you get lost, press A to warp back to the center.
        if (currentState.Buttons.A == ButtonState.Pressed)
        {
            modelPosition = Vector3.Zero;
            modelVelocity = Vector3.Zero;
            modelRotation = 0.0f;
        }
    }
}
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            // Get some input.
            UpdateInput();

            // Add velocity to the current position.
            modelPosition += modelVelocity;

            // Bleed off velocity over time.
            modelVelocity *= 0.95f;

            base.Update(gameTime);

        }

        // Set the position of the model in world space, and set the rotation.
        Vector3 modelPosition = Vector3.Zero;
        float modelRotation = 0.0f;

        // Set the position of the camera in world space, for our view matrix.
        Vector3 cameraPosition = new Vector3(0.0f, 50.0f, 5000.0f);

        protected override void Draw(GameTime gameTime)
        {
            graphics.GraphicsDevice.Clear(Color.CornflowerBlue);

            // Copy any parent transforms.
            Matrix[] transforms = new Matrix[myModel.Bones.Count];
            myModel.CopyAbsoluteBoneTransformsTo(transforms);

            // Draw the model. A model can have multiple meshes, so loop.
            foreach (ModelMesh mesh in myModel.Meshes)
            {
                // This is where the mesh orientation is set, as well as our camera and projection.
                foreach (BasicEffect effect in mesh.Effects)
                {
                    effect.EnableDefaultLighting();
                    effect.World = transforms[mesh.ParentBone.Index] * Matrix.CreateRotationY(modelRotation)
                        * Matrix.CreateTranslation(modelPosition);
                    effect.View = Matrix.CreateLookAt(cameraPosition, Vector3.Zero, Vector3.Up);
                    effect.Projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f),
                        aspectRatio, 1.0f, 10000.0f);
                }
                // Draw the mesh, using the effects set above.
                mesh.Draw();
            }
            base.Draw(gameTime);
        }

    }
}
como já o tenho instalado

o xnagame permite-me por exemplo usar imagens do maia

Compartilhar este post


Link para o post
Compartilhar em outros sites

Faz um bom tempo que não uso XNA, acho que 2 anos, não me lembro de cabeça como fazer a forma de interação que você quer, tenta dar uma pesquisada no google, seguem alguns tópicos que podem lhe ajudar, mas não fazerem exatamente o que você quer:

 

http://bluwiki.com/go/XNA_Tutorials/Mouse_Input

http://www.gamedev.net/community/forums/topic.asp?topic_id=475761

 

Quanto a imagens do Maya, acredito que refere-se a renders 3D, eu utilizo a tecnologia chamada COLLADA para renderizá-las em todas as plataformas que venho desenvolvendo.

 

http://en.wikipedia.org/wiki/COLLADA

 

Só uma dúvida, você é português? :P

Compartilhar este post


Link para o post
Compartilhar em outros sites

o XNAGAMES tb lé objectos feitos no Google ketshup

 

os objectos do google sketchup tambem dá no XNAGAMES

seria possivel pagar o topico anterior pois eu enganei-me a escrever o nome do programa e como não dava para editar tive que criar um novo poste

Compartilhar este post


Link para o post
Compartilhar em outros sites

O XNA é uma framework bem interessante para desenvolver jogos, também comecei com ele, comprei um livro que agora me falha o nome. Ele suporta praticamente todos tipos de importação de gráficos.

 

Tem mais alguma dúvida genérica quanto a desenvolvimento de jogos? Infelizmente não poderei lhe ajudar muito com o XNA.

Compartilhar este post


Link para o post
Compartilhar em outros sites

se soube-se o nome do livro

era porreiro

pois seria mais facil pois não teria que procurar na internet

mas se não te lembrares tb não há problema eu sempre posso usar a net

Compartilhar este post


Link para o post
Compartilhar em outros sites

mas ele suporta o do google

no caso de deia á possivel converter o ficheiro para um que seja compativel com xnagames 3.0

ja agora sabes um bom livro para aprender a mexer com o maia 2011

Compartilhar este post


Link para o post
Compartilhar em outros sites

não estou a conseguir por a ler um custam ficheiro no xnagame

segue-se o codigo

podias dizer a onde esta o problema pois eu não estou a conseguir fazer que ele me lei-a o ficheiro

using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;

namespace BG_3D
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        GameObject terrain = new GameObject();
        GameObject missileLauncherBase = new GameObject();
        GameObject missileLauncherHead = new GameObject();

        const int numMissiles = 20;
        GameObject[] missiles;

        GamePadState previousState;
#if ! XBOX
        KeyboardState previousKeyboardState;
#endif
        const float launcherHeadMuzzleOffset = 20.0f;
        const float missilePower = 20.0f;
        AudioEngine audioEngine;
        SoundBank soundBank;
        WaveBank waveBank;

        Random r = new Random();//cria un mumero aletorio
        const int numEnemyShips = 3;
        GameObject[] enemyShips;
        Vector3 shipMinPosition = new Vector3(-2000.0f,300.0f,-6000.0f);
        Vector3 shipMaxPosition = new Vector3(2000.0f,800.0f,-4000.0f);
        const float shipMinVelocity = 5.0f;
        const float shipMaxVelocity = 10.0f;



        Vector3 cameraPosition = new Vector3(0.0f, 60.0f, 160.0f);
        Vector3 cameraLookAt = new Vector3(0.0f, 50.0f, 0.0f);
        Matrix cameraProjectionMatrix;
        Matrix cameraViewMatrix;

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

        /// <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()
        {
            // TODO: Add your initialization logic here

            base.Initialize();
             this.IsMouseVisible = true;

        }

        /// <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);

            audioEngine = new AudioEngine("Content\\Audio\\ola.xgs");
            waveBank = new WaveBank(audioEngine,"Content\\Audio\\Wave Bank.xwb");
            soundBank = new SoundBank(audioEngine, "Content\\Audio\\Sound Bank.xsb");

            cameraViewMatrix = Matrix.CreateLookAt(
                cameraPosition,
                cameraLookAt,
                Vector3.Up);

            cameraProjectionMatrix = Matrix.CreatePerspectiveFieldOfView(
                MathHelper.ToRadians(45.0f),
                graphics.GraphicsDevice.Viewport.AspectRatio,
                1.0f,
                10000.0f);

            terrain.model = Content.Load<Model>(
                "Models\\terrain");// vai buscar ao modelo terreno

            missileLauncherBase.model = Content.Load<Model>(
                "Models\\launcher_base");
            missileLauncherBase.scale = 0.2f;//vai buscar o lançador de missels
            
            missileLauncherHead.model = Content.Load<Model>(
                "Models\\launcher_head");

            missileLauncherHead.scale = 0.2f;//faz escala do missel

            missileLauncherHead.position = missileLauncherHead.position *
                new Vector3(0.0f, 20.0f, 0.0f);

            missiles = new GameObject[numMissiles];
            for (int i = 0; i < numMissiles; i++)
            {
                missiles[i] = new GameObject();
                missiles[i].model =
                Content.Load<Model>("Models\\missile");
                missiles[i].scale = 3.0f;
                 
            }
            enemyShips = new GameObject[numEnemyShips];
            for (int i = 0; i < numEnemyShips; i++)
            {
                enemyShips[i] = new GameObject();
                enemyShips[i].model = Content.Load<Model>("Models\\enemy");
                enemyShips[i].scale = 0.1f;
                enemyShips[i].rotation = new Vector3(
                    0.0f, MathHelper.Pi, 0.0f);
            }

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

        /// <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();
            MouseState mouseStateCurrent;
            mouseStateCurrent = Mouse.GetState();


            //por o objecto a respoder as teclas
            GamePadState gamePadState = GamePad.GetState(PlayerIndex.One);
            missileLauncherHead.rotation.Y -=
            gamePadState.ThumbSticks.Left.X * 0.1f;

            missileLauncherHead.rotation.Y +=
                gamePadState.ThumbSticks.Left.Y * 0.1f;
#if !XBOX
            KeyboardState keyboardstate = Keyboard.GetState();
            if (keyboardstate.IsKeyDown(Keys.Left))
            {
                missileLauncherHead.rotation.Y += 0.05f;
            }
            if (keyboardstate.IsKeyDown(Keys.Right))
            {
                missileLauncherHead.rotation.Y -= 0.05f;

            }
            if (keyboardstate.IsKeyDown(Keys.Up))
            {
                missileLauncherHead.rotation.X += 0.05f;
            }
            if (keyboardstate.IsKeyDown(Keys.Down))
            {
                missileLauncherHead.rotation.X -= 0.05f;
            }
#endif
            missileLauncherHead.rotation.Y = MathHelper.Clamp(
                missileLauncherHead.rotation.Y,
                -MathHelper.PiOver4, MathHelper.PiOver4);
            missileLauncherHead.rotation.X = MathHelper.Clamp(missileLauncherHead.rotation.X,
                0, MathHelper.PiOver4);

            if (gamePadState.Buttons.A == ButtonState.Pressed &&
                previousState.Buttons.A == ButtonState.Released)
            {
                FireMissile();
            }
#if !XBOX
            if (keyboardstate.IsKeyDown(Keys.Space) &&
                previousKeyboardState.IsKeyUp(Keys.Space))
            {
                FireMissile();
            }

#endif
            UpdateMissiles();

            audioEngine.Update();
            UpdateEnemyShips();

            previousState = gamePadState;

#if !XBOX
            previousKeyboardState = keyboardstate;
            // TODO: Add your update logic here
#endif
            /*#if !XBOX
             

   // Move the sprite to the current mouse position when the left button is pressed
   if (mouseStateCurrent.LeftButton == ButtonState.Pressed)
   {
      missileLauncherHead.rotation.X = mouseStateCurrent.X;
     missileLauncherHead.rotation.Y = mouseStateCurrent.Y;
   }

   // Change the horizontal direction of the sprite when the right mouse button is clicked
  // if (mouseStateCurrent.RightButton == ButtonState.Pressed &&
   //    mouseStatePrevious.RightButton == ButtonState.Released)
  // {
    //   missileLauncherHead.rotation.X *= -1;
   //}
#endif
     */
            base.Update(gameTime);
            //funcão que lança o missils
        }
        void FireMissile()
        {
            foreach (GameObject missile in missiles)
            {
                if (!missile.alive)
                {
                    soundBank.PlayCue("missilelaunch");
                    missile.velocity = GetMissileMuzzleVelocity();
                    missile.position = GetMissileMuzzlePosition();
                    missile.rotation = missileLauncherHead.rotation;
                    missile.alive = true;
                    break;
                }
            }
        }
        Vector3 GetMissileMuzzleVelocity()
        {
            Matrix rotationMatrix =
                Matrix.CreateFromYawPitchRoll(
                missileLauncherHead.rotation.Y,
                missileLauncherHead.rotation.X,
                0);
            return Vector3.Normalize(
                Vector3.Transform(Vector3.Forward,
                rotationMatrix)) * missilePower;
        }
        Vector3 GetMissileMuzzlePosition()
        {
            return missileLauncherHead.position +
                (Vector3.Normalize(
                GetMissileMuzzleVelocity()) *
                launcherHeadMuzzleOffset);
        }

        void UpdateMissiles()
        {
            foreach (GameObject missile in missiles)
            {
                if (missile.alive)
                {
                    missile.position += missile.velocity;
                    if (missile.position.Z < -6000.0f)    //posição do missels
                    {
                        missile.alive = false;
                    }
                    else
                    {
                        TestCollision(missile);
                    }
                }
            }
        }
        void UpdateEnemyShips()
        {
            foreach (GameObject ship in enemyShips)
            {
                if (ship.alive)
                {
                    ship.position += ship.velocity;
                    if (ship.position.Z > 500.0f)
                    {
                        ship.alive = false;
                    }
                }
                else
                {
                    ship.alive = true;
                    ship.position = new Vector3(
                        MathHelper.Lerp(
                        shipMaxPosition.X,
                        shipMinPosition.X,
                        (float)r.NextDouble()),

                        MathHelper.Lerp(
                        shipMinPosition.Y,
                        shipMaxPosition.Y,
                        (float)r.NextDouble()),
                        MathHelper.Lerp(
                        shipMaxPosition.Z,
                        shipMinPosition.Z,
                        (float)r.NextDouble()));
                    ship.velocity = new Vector3(
                        0.0f,
                        0.0f,
                        MathHelper.Lerp(shipMinVelocity, shipMaxVelocity, (float)r.NextDouble()));
                }
            }
        }
        void TestCollision(GameObject missele)
        {
            BoundingSphere misselesphere =
                missele.model.Meshes[0].BoundingSphere;
            misselesphere.Center = missele.position;
            misselesphere.Radius *= missele.scale;
            
            foreach(GameObject ship in enemyShips)
            {
                if(ship.alive)
                {
                   BoundingSphere shipsphere =
                       ship.model.Meshes[0].BoundingSphere;
                    shipsphere.Center = ship.position;
                    shipsphere.Radius *= ship.scale;

                    if(shipsphere.Intersects(misselesphere))
                    {
                        soundBank.PlayCue("explosion");
                        missele.alive = false;
                        ship.alive=false;
                        break;
                    }
                }

            }
            }
        
        /// <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)
        {
            graphics.GraphicsDevice.Clear(Color.CornflowerBlue);

            DrawGameObject(terrain);
            DrawGameObject(missileLauncherBase);
            DrawGameObject(missileLauncherHead);

            foreach (GameObject missile in missiles)
            {
                if (missile.alive)
                {
                    DrawGameObject(missile);
                }
            }
            foreach (GameObject enemyship in enemyShips)
            {
                if (enemyship.alive)
                {
                    DrawGameObject(enemyship);
                }
            }
            // TODO: Add your drawing code here

            base.Draw(gameTime);
        }

        void DrawGameObject(GameObject gameobject)
        {
            foreach (ModelMesh mesh in gameobject.model.Meshes)
            {
                foreach (BasicEffect effect in mesh.Effects)
                {
                    effect.EnableDefaultLighting();
                    effect.PreferPerPixelLighting = true;

                    effect.World =
                        Matrix.CreateFromYawPitchRoll(
                        gameobject.rotation.Y,
                        gameobject.rotation.X,
                        gameobject.rotation.Z) *

                        Matrix.CreateScale(gameobject.scale) *

                        Matrix.CreateTranslation(gameobject.position);

                    effect.Projection = cameraProjectionMatrix;
                    effect.View = cameraViewMatrix;
                }
                mesh.Draw();
            }
        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BG_3D
{
    class ObjImporter
    {
        [ContentImporter(".skp)", CacheImportedData = true, DefaultProcessor = "ModelProcessor")]
    public class ObjImporter : ContentImporter<NodeContent>
    {
        #region Variables


        // Provides the logger and allows for tracking of file dependencies
        ContentImporterContext importerContext;


        // The root NodeContent of our model
        private NodeContent rootNode;

        // All vertex data in the file
        private List<Vector3> positions;
        private List<Vector2> texCoords;
        private List<Vector3> normals;


        // The current mesh being constructed
        private MeshBuilder meshBuilder;

        // Mapping from mesh positions to the complete list of
        // positions for the current mesh
        private int[] positionMap;

        // Indices of vertex channels for the current mesh
        private int textureCoordinateDataIndex;
        private int normalDataIndex;


        // Named materials from all imported MTL files
        private Dictionary<String, MaterialContent> materials;

        // Identity of current MTL file for reporting errors agaisnt
        private ContentIdentity mtlFileIdentity;

        // Current material being constructed
        private BasicMaterialContent materialContent;


        #endregion

        #region Entry point


        /// <summary>
        /// The importer's entry point.
        /// Called by the framework when importing a game asset.
        /// </summary>
        /// <param name="filename">Name of a game asset file.</param>
        /// <param name="context">
        /// Contains information for importing a game asset, such as a logger interface.
        /// </param>
        /// <returns>Resulting game asset.</returns>
        public override NodeContent Import(string filename,
            ContentImporterContext context)
        {
            // Uncomment the following line to debug:
            //System.Diagnostics.Debugger.Launch();

            // Store the context for use in other methods
            importerContext = context;

            // Reset all importer state
            // See field declarations for more information
            rootNode = new NodeContent();            
            positions = new List<Vector3>();
            texCoords = new List<Vector2>();
            normals = new List<Vector3>();
            meshBuilder = null;
            // StartMesh sets positionMap, textureCoordinateDataIndex, normalDataIndex
            materials = new Dictionary<string, MaterialContent>();
            // ImportMaterials resets materialContent

            // Model identity is tied to the file it is loaded from
            rootNode.Identity = new ContentIdentity(filename);

            try
            {
                // Loop over each tokenized line of the OBJ file
                foreach (String[] lineTokens in
                    GetLineTokens(filename, rootNode.Identity))
                {
                    ParseObjLine(lineTokens);
                }

                // If the file did not provide a model name (through an 'o' line),
                // then use the file name as a default
                if (rootNode.Name == null)
                    rootNode.Name = Path.GetFileNameWithoutExtension(filename);

                // Finish the last mesh
                FinishMesh();

                // Done with entire model!
                return rootNode;
            }
            catch (InvalidContentException)
            {
                // InvalidContentExceptions do not need further processing
                throw;
            }
            catch (Exception e)
            {
                // Wrap exception with content identity (includes line number)
                throw new InvalidContentException(
                    "Unable to parse obj file. Exception:\n" + e.Message,
                    rootNode.Identity, e);
            }
        }

        #endregion

        #region Mesh parsing


        /// <summary>
        /// Parses and executes an individual line of an OBJ file.
        /// </summary>
        /// <param name="lineTokens">Line to parse as tokens</param>
        private void ParseObjLine(string[] lineTokens)
        {
            // Switch by line type
            switch (lineTokens[0].ToLower())
            {
                // Object
                case "o":
                    // The next token is the name of the model
                    rootNode.Name = lineTokens[1];
                    break;

                // Positions
                case "v":
                    positions.Add(ParseVector3(lineTokens));
                    break;

                // Texture coordinates
                case "vt":
                {
                    // u is required, but v and w are optional
                    // Require a Vector2 and ignore the w for the sake of this sample
                    Vector2 vt = ParseVector2(lineTokens);

                    // Flip the v coordinate
                    vt.Y = 1 - vt.Y;

                    texCoords.Add(vt);
                    break;
                }

                // Normals
                case "vn":
                    normals.Add(ParseVector3(lineTokens));
                    break;

                // Groups (model meshes)
                case "g":
                    // End the current mesh
                    if (meshBuilder != null)
                        FinishMesh();

                    // Begin a new mesh
                    // The next token is an optional name
                    if (lineTokens.Length > 1)
                        StartMesh(lineTokens[1]);
                    else
                        StartMesh(null);
                    break;

                // Smoothing group
                case "s":
                    // Ignore; just use the normals as specified with verticies
                    break;

                // Faces (only triangles are supported)
                case "f":
                    // Warn about and ignore polygons which are not triangles
                    if (lineTokens.Length > 4)
                    {
                        importerContext.Logger.LogWarning(null, rootNode.Identity,
                            "N-sided polygons are not supported; Ignoring face");
                        break;
                    }

                    // If the builder is null, this face is outside of a group
                    // Start a new, unnamed group
                    if (meshBuilder == null)
                        StartMesh(null);

                    // For each triangle vertex
                    for (int vertexIndex = 1; vertexIndex <= 3; vertexIndex++)
                    {
                        // Each vertex is a set of three indices:
                        // position, texture coordinate, and normal
                        // The indices are 1-based, separated by slashes
                        // and only position is required.
                        string[] indices = lineTokens[vertexIndex].Split('/');

                        // Required: Position
                        int positionIndex = int.Parse(indices[0],
                            CultureInfo.InvariantCulture) - 1;

                        if (indices.Length > 1)
                        {
                            // Optional: Texture coordinate
                            int texCoordIndex;
                            Vector2 texCoord;
                            if (int.TryParse(indices[1], out texCoordIndex))
                                texCoord = texCoords[texCoordIndex - 1];
                            else
                                texCoord = Vector2.Zero;

                            // Set channel data for texture coordinate for the following
                            // vertex. This must be done before calling AddTriangleVertex
                            meshBuilder.SetVertexChannelData(textureCoordinateDataIndex,
                                texCoord);
                        }

                        if (indices.Length > 2)
                        {
                            // Optional: Normal
                            int normalIndex;
                            Vector3 normal;
                            if (int.TryParse(indices[2], out normalIndex))
                                normal = normals[normalIndex - 1];
                            else
                                normal = Vector3.Zero;

                            // Set channel data for normal for the following vertex.
                            // This must be done before calling AddTriangleVertex
                            meshBuilder.SetVertexChannelData(normalDataIndex,
                                normal);

                        }

                        // Add the vertex with the vertex data that was just set
                        meshBuilder.AddTriangleVertex(positionMap[positionIndex]);
                    }
                    break;

                // Import a material library file
                case "mtllib":
                    // Remaining tokens are relative paths to MTL files
                    for (int i = 1; i < lineTokens.Length; i++)
                    {
                        string mtlFileName = lineTokens[i];

                        // A full path is needed,
                        if (!Path.IsPathRooted(mtlFileName))
                        {
                            // resolve relative paths
                            string directory =
                                Path.GetDirectoryName(rootNode.Identity.SourceFilename);
                            mtlFileName = Path.GetFullPath(
                                Path.Combine(directory, mtlFileName));
                        }

                        // By calling AddDependency, we will cause this model
                        // to be rebuilt if its associated MTL files change
                        importerContext.AddDependency(mtlFileName);

                        // Import and record the new materials
                        ImportMaterials(mtlFileName);
                    }
                    break;

                // Apply a material
                case "usemtl":
                {
                    // If the builder is null, OBJ most likely lacks groups
                    // Start a new, unnamed group
                    if (meshBuilder == null)
                        StartMesh(null);

                    // Next token is material name
                    string materialName = lineTokens[1];

                    // Apply the material to the upcoming faces
                    MaterialContent material;
                    if (materials.TryGetValue(materialName, out material))
                        meshBuilder.SetMaterial(material);
                    else
                    {
                        throw new InvalidContentException(String.Format(
                            "Material '{0}' not defined.", materialName),
                            rootNode.Identity);
                    }

                    break;
                }

                // Unsupported or invalid line types
                default:
                    throw new InvalidContentException(
                        "Unsupported or invalid line type '" + lineTokens[0] + "'",
                        rootNode.Identity);
            }
        }


        /// <summary>
        /// Starts a new mesh and fills it with mesh mapped positions.
        /// </summary>
        /// <param name="name">Name of mesh.</param>
        private void StartMesh(string name)
        {
            meshBuilder = MeshBuilder.StartMesh(name);

            // Obj files need their winding orders swapped
            meshBuilder.SwapWindingOrder = true;

            // Add additional vertex channels for texture coordinates and normals
            textureCoordinateDataIndex = meshBuilder.CreateVertexChannel<Vector2>(
                VertexChannelNames.TextureCoordinate(0));
            normalDataIndex =
                meshBuilder.CreateVertexChannel<Vector3>(VertexChannelNames.Normal());

            // Add each position to this mesh with CreatePosition
            positionMap = new int[positions.Count];
            for (int i = 0; i < positions.Count; i++)
            {
                // positionsMap redirects from the original positions in the order
                // they were read from file to indices returned from CreatePosition
                positionMap[i] = meshBuilder.CreatePosition(positions[i]);
            }
        }


        /// <summary>
        /// Finishes building a mesh and adds the resulting MeshContent or
        /// NodeContent to the root model's NodeContent.
        /// </summary>
        private void FinishMesh()
        {
            MeshContent meshContent = meshBuilder.FinishMesh();

            // Groups without any geometry are just for transform
            if (meshContent.Geometry.Count > 0)
            {
                // Add the mesh to the model
                rootNode.Children.Add(meshContent);
            }
            else
            {
                // Convert to a general NodeContent
                NodeContent nodeContent = new NodeContent();
                nodeContent.Name = meshContent.Name;

                // Add the transform-only node to the model
                rootNode.Children.Add(nodeContent);
            }

            meshBuilder = null;
        }


        #endregion

        #region Material parsing


        /// <summary>
        /// Parses an MTL file and adds all its materials to the materials collection
        /// </summary>
        /// <param name="filename">Full path of MTL file.</param>
        private void ImportMaterials(string filename)
        {
            // Material library identity is tied to the file it is loaded from
            mtlFileIdentity = new ContentIdentity(filename);
            
            // Reset the current material
            materialContent = null;

            try
            {
                // Loop over each tokenized line of the MTL file
                foreach (String[] lineTokens in
                    GetLineTokens(filename, mtlFileIdentity))
                {
                    ParseMtlLine(lineTokens);
                }
            }
            catch (InvalidContentException)
            {
                // InvalidContentExceptions do not need further processing
                throw;
            }
            catch (Exception e)
            {
                // Wrap exception with content identity (includes line number)
                throw new InvalidContentException(
                    "Unable to parse mtl file. Exception:\n" + e.Message,
                    mtlFileIdentity, e);
            }

            // Finish the last material
            if (materialContent != null)
                materials.Add(materialContent.Name, materialContent);
        }


        /// <summary>
        /// Parses and executes an individual line of a MTL file.
        /// </summary>
        /// <param name="lineTokens">Line to parse as tokens</param>
        void ParseMtlLine(string[] lineTokens)
        {
            // Switch on line type
            switch (lineTokens[0].ToLower())
            {
                // New material
                case "newmtl":
                    // Finish the current material
                    if (materialContent != null)
                        materials.Add(materialContent.Name, materialContent);

                    // Start a new material
                    materialContent = new BasicMaterialContent();
                    materialContent.Identity =
                        new ContentIdentity(mtlFileIdentity.SourceFilename);

                    // Next token is new material's name
                    materialContent.Name = lineTokens[1];
                    break;

                // Diffuse color
                case "kd":
                    materialContent.DiffuseColor = ParseVector3(lineTokens);
                    break;

                // Diffuse texture
                case "map_kd":
                    // Reference a texture relative to this MTL file
                    materialContent.Texture = new ExternalReference<TextureContent>(
                        lineTokens[1], mtlFileIdentity);
                    break;

                // Ambient color
                case "ka":
                    // Ignore ambient color because it should be set by scene lights
                    break;

                // Specular color
                case "ks":
                    materialContent.SpecularColor = ParseVector3(lineTokens);
                    break;

                // Specular power
                case "ns":
                    materialContent.SpecularPower = float.Parse(lineTokens[1],
                            CultureInfo.InvariantCulture);
                    break;

                // Emissive color
                case "ke":
                    materialContent.EmissiveColor = ParseVector3(lineTokens);
                    break;

                // Alpha
                case "d":
                    materialContent.Alpha = float.Parse(lineTokens[1],
                            CultureInfo.InvariantCulture);
                    break;

                // Illumination mode (0=constant, 1=diffuse, 2=diffuse+specular)
                case "illum":
                    // Store as opaque data. This alllows the rendering engine to
                    // interpret this data if it likes. For example, it can set
                    // constant constant illumination mode by dissabling lighting
                    // on the BasicEffect.
                    materialContent.OpaqueData.Add("Illumination mode",
                        int.Parse(lineTokens[1], CultureInfo.InvariantCulture));
                    break;

                // Unsupported or invalid line types
                default:
                    throw new InvalidContentException(
                        "Unsupported or invalid line type '" + lineTokens[0] + "'",
                        mtlFileIdentity);
            }
        }


        #endregion

        #region Shared parsing helpers


        /// <summary>
        /// Yields an array of tokens for each line in an OBJ or MTL file.
        /// </summary>
        /// <remarks>
        /// OBJ and MTL files are text based formats of identical structure.
        /// Each line of a OBJ or MTL file is either an instruction or a comment.
        /// Comments begin with # and are effectively ignored.
        /// Instructions are a space dilimited list of tokens. The first token is the
        /// instruction type code. The tokens which follow, are the arguments to that
        /// instruction. The number and format of arguments vary by instruction type.
        /// </remarks>
        /// <param name="filename">Full path of file to read.</param>
        /// <param name="identity">Identity of the file being read. This is modified to
        /// include the current line number in case an exception is thrown.</param>
        /// <returns>Element 0 is the line type identifier. The remaining elements are
        /// arguments to the identifier's operation.</returns>
        private static IEnumerable<string[]> GetLineTokens(string filename,
            ContentIdentity identity)
        {
            // Open the file
            using (StreamReader reader = new StreamReader(filename))
            {
                int lineNumber = 1;

                // For each line of the file
                while (!reader.EndOfStream)
                {
                    // Set the line number to report in case an exception is thrown
                    identity.FragmentIdentifier = lineNumber.ToString();

                    // Tokenize line by splitting on 1 more more whitespace character
                    string[] lineTokens = Regex.Split(reader.ReadLine().Trim(), @"\s+");

                    // Skip blank lines and comments
                    if (lineTokens.Length > 0 &&
                        lineTokens[0] != String.Empty &&
                        !lineTokens[0].StartsWith("#"))
                    {
                        // Pass off the tokens of this line to be processed
                        yield return lineTokens;
                    }

                    // Done with this line!
                    lineNumber++;
                }


                // Clear line number from identity
                identity.FragmentIdentifier = null;
            }
        }


        /// <summary>
        /// Parses a Vector2 from tokens of an OBJ file line.
        /// </summary>
        /// <param name="lineTokens">X and Y coordinates in lineTokens[1 through 2].
        /// </param>
        private static Vector2 ParseVector2(string[] lineTokens)
        {
            return new Vector2(
                float.Parse(lineTokens[1], CultureInfo.InvariantCulture),
                float.Parse(lineTokens[2], CultureInfo.InvariantCulture));
        }


        /// <summary>
        /// Parses a Vector3 from tokens of an OBJ file line.
        /// </summary>
        /// <param name="lineTokens">X,Y and Z coordinates in lineTokens[1 through 3].
        /// </param>
        private static Vector3 ParseVector3(string[] lineTokens)
        {
            return new Vector3(
                float.Parse(lineTokens[1], CultureInfo.InvariantCulture),
                float.Parse(lineTokens[2], CultureInfo.InvariantCulture),
                float.Parse(lineTokens[3], CultureInfo.InvariantCulture));
        }


        #endregion
    }
}

    }

Compartilhar este post


Link para o post
Compartilhar em outros sites

Como já disse anteriormente não tenho conhecimentos profissionais em XNA, então não posso lhe ajudar nessa parte.

 

O que posso lhe ajudar é sobre processo de criação de games, lógica de games, física, ou seja, assuntos gerais, específicos por enquanto apenas C++ e Actionscript 3.0, no caso de bugs em códigos.

 

Favor sempre postar juntamente de um código, o erro e a linha de código que isso está causando.

 

Mais alguma dúvida?

Compartilhar este post


Link para o post
Compartilhar em outros sites

ja resolvi o problema

vou usar o autodesk 3d max studio 2011

em versão trial

pois o tipo de ficheiro é compatível com o xnagames na versão nativa

o livro que me aconselhou é mesmo muito bom

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.