2012-11-25 4 views
1

게임용, 모델 용 및 카메라 용의 3 가지 클래스를 만들었습니다. 내 카메라가 움직일 때 내 모델을 따르기를 원하지만 내 모델은 더 이상 나타나지 않습니다. 누구든지 내 카메라 및/또는 게임 수업에서 내가 뭘 잘못하고 있는지 알 수 있습니까?XNA C# 카메라 및 모델


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; 
    } 
} 
} 

+0

정말 많은 공백과 주석 처리 된 코드가 있습니까? 조직화되지 않았고 읽기/유지가 어렵다는 것을 알지 못합니까? –

답변

3

첫째, 당신은 당신이 각 개체 클래스를 생성, 코드를 구성하는 방법을 배워야한다하지만 당신은 여전히 ​​처리의 일부를 수행 각 객체와 일부 게임에서 이것은 매우 지저분합니다!

카메라가 작동하지 않는 이유에 대한 간단한 대답은 단순히 사용하지 않기 때문입니다! 당신의 ViewMatrixProjectionMatrix 적용을하기에 충분 수도

당신은 당신의 DrawModelcam1.SetupEffectDefaults(model); 뭔가를 추가, 당신의 코드를 간략하게보고에서하지만, this one처럼, XNA에 카메라를 만드는 방법에 대한 적절한 튜토리얼을 따라한다. 초기화 단계에서이 행렬을 호출하면 게임 중에 업데이트되는 행렬이 많아지지 않습니다.

+0

나는 당신이 나에게 준 그 혀를 따라 갔다. 나는 혼란스러워했다. this._camera = new Camera (graphics.GraphicsDevice.Viewport); this._camera.LookAt = new Vector3 (0.0f, 0.0f, -1.0f); 나는 그것을 어디에 두어야합니까? – steven

+1

@steven이 줄 바로 앞에 '줄을 짓고있는 동안 카메라를 초기화하십시오.'라고 말합니다. 코드를 사용하면'graphics' 객체를 만든 후에'public Game1()'에 있다고 말할 수 있습니다! – emartel

+0

계속해서 test1.Game1에 "_camera"에 대한 정의가없고 확장 메서드 "_camera"가 없습니다. – steven