XNA Game Engine教程系列7 – 第一人称视点相机

此教程讨论建立一个第一人称视点相机,这种类型的相机现今被用在了很多游戏中,它能移动和旋转。以后我们会讨论如何对相机设置物理效果,这样它就能和周围环境发生互动。

using Microsoft.Xna.Framework;
using System;

namespace Innovation
{
    // A simple first person camera. Accepts rotation and translation
    public class FPSCamera : Camera
    {
        // Keeps track of the rotation and translation that have been
        // added via RotateTranslate()
        Vector3 rotation;
        Vector3 translation;

        public FPSCamera(GameScreen Parent) : base(Parent) { }
        public FPSCamera() : base() { }

        // This adds to rotation and translation to change the camera view
        public void RotateTranslate(Vector3 Rotation, Vector3 Translation)
        {
            translation += Translation;
            rotation += Rotation;
        }

        public override void Update()
        {
            // Update the rotation matrix using the rotation vector
            Rotation = MathUtil.Vector3ToMatrix(rotation);

            // Update the position in the direction of rotation
            translation = Vector3.Transform(translation, Rotation);
            Position += translation;

            // Reset translation
            translation = Vector3.Zero;

            // Calculate the new target
            Target = Vector3.Add(Position, Rotation.Forward);

            // Have the base Camera update all the matrices, etc.
            base.Update();
        }
    }
}

下面的代码是如何在游戏中使用相机,首先要在LoadContent()方法中建立一个FPSCamera。

KeyboardDevice keyboard = Engine.Services.GetService<KeyboardDevice>();
MouseDevice mouse = Engine.Services.GetService<MouseDevice>();
FPSCamera cam = (FPSCamera)Engine.Services.GetService<Camera>();

Vector3 inputModifier = new Vector3(
    (keyboard.IsKeyDown(Keys.A) ? -1 : 0) + (keyboard.IsKeyDown(Keys.D) ? 1 : 0),
    (keyboard.IsKeyDown(Keys.Q) ? -1 : 0) + (keyboard.IsKeyDown(Keys.E) ? 1 : 0),
    (keyboard.IsKeyDown(Keys.W) ? -1 : 0) + (keyboard.IsKeyDown(Keys.S) ? 1 : 0)
);

cam.RotateTranslate(new Vector3(mouse.Delta.Y * -.002f, mouse.Delta.X * -.002f, 0), inputModifier * .05f);

if (mouse.WasButtonPressed(MouseButtons.Left))
{
    PhysicsActor act = new PhysicsActor(
        Engine.Content.Load<Model>("Content/ig_box"),
        new BoxObject(new Vector3(.5f), cam.Position, Vector3.Zero));

    act.Scale = new Vector3(.5f);
    act.PhysicsObject.Mass = 1000;

    Vector3 dir = cam.Target - cam.Position;
    dir.Normalize();

    act.PhysicsObject.Velocity = dir * 10;
}

点击鼠标你能从相机视点发射一个盒子。


发布时间:2009/2/6 7:51:53  阅读次数:6043

2006 - 2024,推荐分辨率1024*768以上,推荐浏览器Chrome、Edge等现代浏览器,截止2021年12月5日的访问次数:1872万9823 站长邮箱

沪ICP备18037240号-1

沪公网安备 31011002002865号