将矢量坐标显示为字符串值

时间:2013-11-12 14:09:57

标签: c# vector static xna draw

我现在正在尝试显示一个矢量,其中包含一个精灵的X和Y值,从一个类Game Object.csGame1.cs。当我将它移到draw方法上时,我将受保护的值(protected Vector2 velocity;)移动到public Vector2 velocity(这样它将显示屏幕上的精灵移动的速度)它出现{{1} }。所以我添加静态,现在是Error 1 An object reference is required for the non-static field, method, or property,然后玩游戏。当我看到X和Y值时,它们会在那里,但是当我移动时它们不会改变。我有任何静态的问题。

有没有办法摆脱静态,或修复此问题,以便在播放时我可以看到X和Y更新?我在public static Vector2 velocitys的更新中使用velocitys向量获取velocity的X和Y,这样它就会不断地从速度中获取。

为什么需要静电?我可以改变吗?我可以在屏幕上更新吗?

这是代码:

GameObject.cs:

(Holdes the Vectors的速度和速度)

GameObject.cs

Game1.cs:

(绘制Vector2速度)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Tile_Engine;

namespace **
{
public class GameObject
{
    #region Declarations
    protected Vector2 worldLocation;
    protected Vector2 velocity;
    protected int frameWidth;
    protected int frameHeight;

    protected bool enabled;
    protected bool flipped = false;
    protected bool onGround;

    protected Rectangle collisionRectangle;
    protected int collideWidth;
    protected int collideHeight;
    protected bool codeBasedBlocks = true;

    protected float drawDepth = 0.85f;
    protected Dictionary<string, AnimationStrip> animations =
        new Dictionary<string, AnimationStrip>();
    protected string currentAnimation;

    public Vector2 velocitys;
    #endregion

    #region Properties
    public bool Enabled
    {
        get { return enabled; }
        set { enabled = value; }
    }

    public Vector2 WorldLocation
    {
        get { return worldLocation; }
        set { worldLocation = value; }
    }

    public Vector2 WorldCenter
    {
        get
        {
            return new Vector2(
                (int)worldLocation.X + (int)(frameWidth / 2),
                (int)worldLocation.Y + (int)(frameHeight / 2));
        }
    }

    public Rectangle WorldRectangle
    {
        get
        {
            return new Rectangle(
                (int)worldLocation.X,
                (int)worldLocation.Y,
                frameWidth,
                frameHeight);
        }
    }

    public Rectangle CollisionRectangle
    {
        get
        {
            return new Rectangle(
                (int)worldLocation.X + collisionRectangle.X,
                (int)worldLocation.Y + collisionRectangle.Y,
                collisionRectangle.Width,
                collisionRectangle.Height);
        }
        set { collisionRectangle = value; }
    }
    #endregion

    #region Helper Methods
    private void updateAnimation(GameTime gameTime)
    {
        if (animations.ContainsKey(currentAnimation))
        {
            if (animations[currentAnimation].FinishedPlaying)
            {
                PlayAnimation(animations[currentAnimation].NextAnimation);
            }
            else
            {
                animations[currentAnimation].Update(gameTime);
            }
        }
    }
    #endregion

    #region Public Methods
    public void PlayAnimation(string name)
    {
        if (!(name == null) && animations.ContainsKey(name))
        {
            currentAnimation = name;
            animations[name].Play();
        }
    }

    public virtual void Update(GameTime gameTime)
    {
        if (!enabled)
            return;

        float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;

        updateAnimation(gameTime);

        if (velocity.Y != 0)
        {
            velocitys = velocity;
            onGround = false;
        }

        Vector2 moveAmount = velocity * elapsed;

        moveAmount = horizontalCollisionTest(moveAmount);
        moveAmount = verticalCollisionTest(moveAmount);

        Vector2 newPosition = worldLocation + moveAmount;

        newPosition = new Vector2(
            MathHelper.Clamp(newPosition.X, 0,
            Camera.WorldRectangle.Width - frameWidth),
            MathHelper.Clamp(newPosition.Y, 2 * (-TileMap.TileHeight),
            Camera.WorldRectangle.Height - frameHeight));

        worldLocation = newPosition;
    }

    public virtual void Draw(SpriteBatch spriteBatch)
    {
        if (!enabled)
            return;
        if (animations.ContainsKey(currentAnimation))
        {
            SpriteEffects effect = SpriteEffects.None;

            if (flipped)
            {
                effect = SpriteEffects.FlipHorizontally;
            }

            spriteBatch.Draw(
                animations[currentAnimation].Texture,
                Camera.WorldToScreen(WorldRectangle),
                animations[currentAnimation].FrameRectangle,
                Color.White, 0.0f, Vector2.Zero, effect, drawDepth);
        }
    }
    #endregion

    #region Map-Based Collision Detecting Methods
    private Vector2 horizontalCollisionTest(Vector2 moveAmount)
    {
        if (moveAmount.X == 0)
            return moveAmount;

        Rectangle afterMoveRect = CollisionRectangle;
        afterMoveRect.Offset((int)moveAmount.X, 0);
        Vector2 corner1, corner2;

        if (moveAmount.X < 0)
        {
            corner1 = new Vector2(afterMoveRect.Left,
                afterMoveRect.Top + 1);
            corner2 = new Vector2(afterMoveRect.Left,
                afterMoveRect.Bottom - 1);
        }
        else
        {
            corner1 = new Vector2(afterMoveRect.Right,
                afterMoveRect.Top + 1);
            corner2 = new Vector2(afterMoveRect.Right,
                afterMoveRect.Bottom - 1);
        }

        Vector2 mapCell1 = TileMap.GetCellByPixel(corner1);
        Vector2 mapCell2 = TileMap.GetCellByPixel(corner2);

        if (!TileMap.CellIsPassable(mapCell1) ||
            !TileMap.CellIsPassable(mapCell2))
        {
            moveAmount.X = 0;
            velocity.X = 0;
        }

        if (codeBasedBlocks)
        {
            if (TileMap.CellCodeValue(mapCell1) == "BLOCK" ||
                TileMap.CellCodeValue(mapCell2) == "BLOCK")
            {
                moveAmount.X = 0;
                velocity.X = 0;
            }
        }
        return moveAmount;
    }

    private Vector2 verticalCollisionTest(Vector2 moveAmount)
    {
        if (moveAmount.Y == 0)
            return moveAmount;

        Rectangle afterMoveRect = CollisionRectangle;
        afterMoveRect.Offset((int)moveAmount.X, (int)moveAmount.Y);
        Vector2 corner1, corner2;

        if (moveAmount.Y < 0)
        {
            corner1 = new Vector2(afterMoveRect.Left + 1,
                afterMoveRect.Top);
            corner2 = new Vector2(afterMoveRect.Right - 1,
                afterMoveRect.Top);
        }
        else
        {
            corner1 = new Vector2(afterMoveRect.Left + 1,
                afterMoveRect.Bottom);
            corner2 = new Vector2(afterMoveRect.Right - 1,
                afterMoveRect.Bottom);
        }
        Vector2 mapCell1 = TileMap.GetCellByPixel(corner1);
        Vector2 mapCell2 = TileMap.GetCellByPixel(corner2);

        if (!TileMap.CellIsPassable(mapCell1) ||
            !TileMap.CellIsPassable(mapCell2))
        {
            if (moveAmount.Y > 0)
                onGround = true;
            moveAmount.Y = 0;
            velocity.Y = 0;
        }

        if (codeBasedBlocks)
        {
            if (TileMap.CellCodeValue(mapCell1) == "BLOCK" ||
                TileMap.CellCodeValue(mapCell2) == "BLOCK")
            {
                if (moveAmount.Y > 0)
                    onGround = true;
                moveAmount.Y = 0;
                velocity.Y = 0;
            }
        }
        return moveAmount;
    }
    #endregion
}
}

Player.cs:

(速度的一部分)

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

namespace **
{
public class Game1 : Microsoft.Xna.Framework.Game
{
    GraphicsDeviceManager graphics;
    SpriteBatch spriteBatch;
    Player player;

    SpriteFont pericles8;
    Vector2 scorePosition = new Vector2(20, 580);

    enum GameState { TitleScreen, Playing, PlayerDead, GameOver };
    GameState gameState = GameState.TitleScreen;

    Vector2 gameOverPosition = new Vector2(350, 300);
    Vector2 livesPosition = new Vector2(600, 580);
    Vector2 Velocitys = new Vector2(100, 580);

    Texture2D titleScreen;

    float deathTimer = 0.0f;
    float deathDelay = 5.0f;

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

    protected override void Initialize()
    {
        // TODO: Add your initialization logic here

        this.graphics.PreferredBackBufferWidth = 800;
        this.graphics.PreferredBackBufferHeight = 600;
        this.graphics.ApplyChanges();

        base.Initialize();
    }

    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);

        TileMap.Initialize(
            Content.Load<Texture2D>(@"Textures\PlatformTiles"));
        TileMap.spriteFont =
            Content.Load<SpriteFont>(@"Fonts\Pericles8");

        pericles8 = Content.Load<SpriteFont>(@"Fonts\Pericles8");
        titleScreen = Content.Load<Texture2D>(@"Textures\TitleScreen");

        Camera.WorldRectangle = new Rectangle(0, 0, 160 * 48, 12 * 48);
        Camera.Position = Vector2.Zero;
        Camera.ViewPortWidth = 800;
        Camera.ViewPortHeight = 600;

        player = new Player(Content);
        LevelManager.Initialize(Content, player);
    }

    protected override void UnloadContent()
    {
        // TODO: Unload any non ContentManager content here
    }

    protected override void Update(GameTime gameTime)
    {
        // Allows the game to exit
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            this.Exit();

        KeyboardState keyState = Keyboard.GetState();
        GamePadState gamepadState = GamePad.GetState(PlayerIndex.One);
        float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;

        if (gameState == GameState.TitleScreen)
        {
            if (keyState.IsKeyDown(Keys.Space) ||
                gamepadState.Buttons.A == ButtonState.Pressed)
            {
                StartNewGame();
                gameState = GameState.Playing;
            }
        }

        if (gameState == GameState.Playing)
        {
            player.Update(gameTime);
            LevelManager.Update(gameTime);
            if (player.Dead)
            {
                if (player.LivesRemaining > 0)
                {
                    gameState = GameState.PlayerDead;
                    deathTimer = 0.0f;
                }
                else{
                    gameState = GameState.GameOver;
                    deathTimer = 0.0f;
                }
            }
        }

        if (gameState == GameState.PlayerDead)
        {
            player.Update(gameTime);
            LevelManager.Update(gameTime);
            deathTimer = elapsed;
            if (deathTimer > deathDelay)
            {
                player.WorldLocation = Vector2.Zero;
                LevelManager.ReloadLevel();
                player.Revive();
                gameState = GameState.Playing;
            }
        }
        if (gameState == GameState.GameOver)
        {
            deathTimer += elapsed;
            if (deathTimer > deathDelay)
            {
                gameState = GameState.TitleScreen;
            }
        }
        base.Update(gameTime);
    }

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

        // TODO: Add your drawing code here

        spriteBatch.Begin(
            SpriteSortMode.BackToFront,
            BlendState.AlphaBlend);
        if (gameState == GameState.TitleScreen)
        {
            spriteBatch.Draw(titleScreen, Vector2.Zero, Color.White);
        }
        if ((gameState == GameState.Playing) ||
            (gameState == GameState.PlayerDead) ||
            (gameState == GameState.GameOver))
        {
            TileMap.Draw(spriteBatch);
            player.Draw(spriteBatch);
            LevelManager.Draw(spriteBatch);
            spriteBatch.DrawString(
                pericles8,
                "Score: " + player.Score.ToString(),
                scorePosition,
                Color.White);
            spriteBatch.DrawString(
                pericles8,
                "Lives Remaining: " + player.LivesRemaining.ToString(),
            livesPosition,
            Color.White);
            spriteBatch.DrawString(
                pericles8,
                "Velocity: " + GameObject.velocitys.ToString(),
                Velocitys,
                Color.White);
        }

        if (gameState == GameState.PlayerDead)
        {
        }
        if (gameState == GameState.GameOver)
        {
            spriteBatch.DrawString(
                pericles8,
                "G A M E  O V E R !",
                gameOverPosition,
                Color.White);
        }
        spriteBatch.End();
        base.Draw(gameTime);
    }

    private void StartNewGame()
    {
        player.Revive();
        player.LivesRemaining = 3;
        player.WorldLocation = Vector2.Zero;
        LevelManager.LoadLevel(0);
    }
}
}

1 个答案:

答案 0 :(得分:0)

我已经想到了自己,我大多想要快速回答。只是制作一个公共向量并没有帮助,我需要一种方法来转移Vector:

public Vector2 Velocitys
{
    get { return velocity; }
    set { velocity = value; }
}

然后就像我绘制的public int Score方法一样:

spriteBatch.DrawString(
                pericles8,
                "Velocity: " + player.Velocitys.ToString(),
                Velocitys,
                Color.White);

它就像一个魅力。

(非常讽刺的是,我问我为什么要使用它(获取和设置)的一件事就是答案)