【问题标题】:XNA C# Camera and modelXNA C# 相机和型号
【发布时间】:2012-11-13 09:47:49
【问题描述】:

我创建了 3 个类:一个用于游戏,一个用于模型,一个用于相机。我希望我的相机在移动时跟随我的模型,但我的模型不再出现。有谁知道我在相机和/或游戏课上做错了什么?


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;

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



    //Visual components
    Ship ship = new Ship();
    Cam cam1 = new Cam();        




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

    protected override void LoadContent()
    {
        ship.Model = Content.Load<Model>("Models/p1_wedge");
        ship.Transforms = cam1.SetupEffectDefaults(ship.Model);            
    }

    protected override void Update(GameTime gameTime)
    {

        // Allows the game to exit
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed ||
            Keyboard.GetState().IsKeyDown(Keys.Escape))
            this.Exit();

        // Get some input.
        UpdateInput();

        // Add velocity to the current position.
        ship.Position += ship.Velocity;
        cam1.cameraPosition += cam1.cameraTarget;
        // Bleed off velocity over time.
        ship.Velocity *= 0.95f;
        cam1.cameraTarget *= 0.95f;

        base.Update(gameTime);
    }

    protected void UpdateInput()
    {
        // Get the game pad state.
        GamePadState currentState = GamePad.GetState(PlayerIndex.One);
        KeyboardState currentKeyState = Keyboard.GetState();

            ship.Update(currentState);
            cam1.Update(currentState);

            // In case you get lost, press A to warp back to the center.
            if (currentState.Buttons.A == ButtonState.Pressed || currentKeyState.IsKeyDown(Keys.Enter))
            {
                ship.Position = Vector3.Zero;
                ship.Velocity = Vector3.Zero;
                ship.Rotation = 0.0f;                  
            }            
    }

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

        Matrix shipTransformMatrix = ship.RotationMatrix
                * Matrix.CreateTranslation(ship.Position);
        DrawModel(ship.Model, shipTransformMatrix, ship.Transforms);
        base.Draw(gameTime);
    }


    public static void DrawModel(Model model, Matrix modelTransform,
Matrix[] absoluteBoneTransforms)
    {
        //Draw the model, a model can have multiple meshes, so loop
        foreach (ModelMesh mesh in model.Meshes)
        {
            //This is where the mesh orientation is set
            foreach (BasicEffect effect in mesh.Effects)
            {
                effect.World =
                    absoluteBoneTransforms[mesh.ParentBone.Index] *
                    modelTransform;
            }
            //Draw the mesh, will use the effects set above.
            mesh.Draw();
        }
    }
}
}

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;


namespace test1
{
class Ship
{
    public Model Model;
    public Matrix[] Transforms;

    //Position of the model in world space
    public Vector3 Position = Vector3.Zero;

    //Velocity of the model, applied each frame to the model's position
    public Vector3 Velocity = Vector3.Zero;
    private const float VelocityScale = 5.0f;

    public Matrix RotationMatrix =
 Matrix.CreateRotationX(MathHelper.PiOver2);

    private float rotation;

    public float Rotation
    {
        get { return rotation; }
        set
        {
            float newVal = value;
            while (newVal >= MathHelper.TwoPi)
            {
                newVal -= MathHelper.TwoPi;
            }
            while (newVal < 0)
            {
                newVal += MathHelper.TwoPi;
            }

            if (rotation != value)
            {
                rotation = value;
                RotationMatrix =
                    Matrix.CreateRotationX(MathHelper.PiOver2) *
                    Matrix.CreateRotationZ(rotation);
            }

        }
    }

    public void Update(GamePadState controllerState)
    {

        KeyboardState currentKeyState = Keyboard.GetState();
        if (currentKeyState.IsKeyDown(Keys.A))
            Rotation += 0.10f;
        else
        // Rotate the model using the left thumbstick, and scale it down.
        Rotation -= controllerState.ThumbSticks.Left.X * 0.10f;

        if (currentKeyState.IsKeyDown(Keys.D))
            Rotation -= 0.10f;

        if (currentKeyState.IsKeyDown(Keys.W))
            Velocity += RotationMatrix.Forward * VelocityScale;
        else
        // Finally, add this vector to our velocity.
        Velocity += RotationMatrix.Forward * VelocityScale *
         controllerState.Triggers.Right;
    }  

}
}

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;


namespace test1
{
class Cam : Microsoft.Xna.Framework.Game
{
    public Vector3 cameraPosition = new Vector3(0.0f, 2000.0f, 25000.0f);
    public Vector3 cameraTarget = Vector3.Zero;

   Matrix projectionMatrix;
    Matrix viewMatrix;

    protected override void Initialize(){

            projectionMatrix = Matrix.CreatePerspectiveFieldOfView(
       MathHelper.ToRadians(45.0f),
       GraphicsDevice.DisplayMode.AspectRatio,
       20000.0f, 30000.0f);

        viewMatrix = Matrix.CreateLookAt(cameraPosition,
            cameraTarget, Vector3.Up);

        base.Initialize();            
    }

    public Matrix[] SetupEffectDefaults(Model myModel)
    {
        Matrix[] absoluteTransforms = new Matrix[myModel.Bones.Count];
        myModel.CopyAbsoluteBoneTransformsTo(absoluteTransforms);

        foreach (ModelMesh mesh in myModel.Meshes)
        {
            foreach (BasicEffect effect in mesh.Effects)
            {
                effect.EnableDefaultLighting();
                effect.Projection = projectionMatrix;
                effect.View = viewMatrix;
            }
        }
        return absoluteTransforms;
    }

    private const float VelocityScale = 5.0f;

    public Matrix RotationMatrix =
 Matrix.CreateRotationX(MathHelper.PiOver2);

    private float rotation;

    public float Rotation
    {
        get { return rotation; }
        set
        {
            float newVal = value;
            while (newVal >= MathHelper.TwoPi)
            {
                newVal -= MathHelper.TwoPi;
            }
            while (newVal < 0)
            {
                newVal += MathHelper.TwoPi;
            }

            if (rotation != value)
            {
                rotation = value;
                RotationMatrix =
                    Matrix.CreateRotationX(MathHelper.PiOver2) *
                    Matrix.CreateRotationZ(rotation);
            }
        }
    }

    public void Update(GamePadState controllerState)
    {
        KeyboardState currentKeyState = Keyboard.GetState();
        if (currentKeyState.IsKeyDown(Keys.A))
            Rotation += 0.10f;
        else
            // Rotate the model using the left thumbstick, and scale it down.
            Rotation -= controllerState.ThumbSticks.Left.X * 0.10f;

        if (currentKeyState.IsKeyDown(Keys.D))
            Rotation -= 0.10f;

        if (currentKeyState.IsKeyDown(Keys.W))
            cameraTarget += RotationMatrix.Forward * VelocityScale;
        else
            // Finally, add this vector to our velocity.
            cameraTarget += RotationMatrix.Forward * VelocityScale *
             controllerState.Triggers.Right;
    }
}
}

【问题讨论】:

  • 你真的有那么多空白和注释掉的代码吗?您不觉得它杂乱无章且难以阅读/维护吗?

标签: c# xna camera 3d-model


【解决方案1】:

首先,你应该学习如何组织你的代码,你为每个对象创建了类,但你仍然在每个对象和游戏中进行一些处理,这非常混乱!

为什么您的相机不工作的简短答案仅仅是因为您没有使用它!

您应该遵循有关在 XNA 中创建相机的正确教程,例如 this one,但是通过简要查看您的代码,在您的 DrawModel 中添加类似 cam1.SetupEffectDefaults(model); 的内容可能足以让您的 ViewMatrixProjectionMatrix 已申请。在初始化阶段调用它不会有太大作用,因为这些矩阵会在游戏期间更新。

【讨论】:

  • 我在关注你给我的那个 tut,我很困惑:this._camera = new Camera(graphics.GraphicsDevice.Viewport); this._camera.LookAt = new Vector3(0.0f, 0.0f, -1.0f);我把它放在哪里?
  • @steven 这些行之前的行说During construction of your game you initialize your camera。使用您的代码,我会说它在 public Game1() 中,在创建 graphics 对象之后!
  • 我不断收到 test1.Game1 不包含“_camera”的定义,也没有扩展方法“_camera”
  • @steven 那是因为你的Game1 类中需要一个Camera _camera;。如果您使用本教程中的代码,则应删除您的 cam1
  • 谢谢,会生效的。View = this._camera.ViewMatrix;效果.Projection = this._camera.ProjectionMatrix;也进入draw方法?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-07
相关资源
最近更新 更多