所以这是我第一次创建类和设置父子层次结构。
在这个课程中,我创建了一个十字准线,然后在 PlayerClasses.cs 中创建了一个球员。我设法为十字准线设置我的屏幕边界没有问题。我认为在Updateme
中使用相同的代码可以使用该船。但事实并非如此,我对此感到有点恼火。
麻烦的是我不知道我打的是什么矩形。我推测它会像我编码m_rect
一样,但它似乎不起作用,我们将不胜感激!
下面我发布了无效的代码部分,后面是该类的整个代码。
public void Updateme(KeyboardState kb, GameTime gt)
{
m_velocity = Vector2.Zero;
if (kb.IsKeyDown(Keys.W))
m_velocity.Y = -1;
if (kb.IsKeyDown(Keys.S))
m_velocity.Y = 1;
if (kb.IsKeyDown(Keys.A))
m_velocity.X = -1;
if (kb.IsKeyDown(Keys.D))
m_velocity.X = 1;
m_position += m_velocity;
// Extra Task 1 PlayerShip Screenbounds
#region Extra task1
if (m_rect.X > 800)
{
m_rect.X = 800;
}
if (m_rect.X < 0)
{
m_rect.X = 0;
}
if (m_rect.Y > 480)
{
m_rect.Y = 480;
}
if (m_rect.Y < 0)
{
m_rect.Y = 0;
}
#endregion Extra task1
整个代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Sidescroller;
using Microsoft.Xna.Framework.Input;
namespace Sidescroller
{
class Crosshair : StaticGraphic
{
private Color m_tint;
private Vector2 m_center;
public Crosshair(Rectangle rect, Texture2D txr, Color tint)
: base(rect, txr)
{
m_tint = tint;
m_center = new Vector2(m_rect.Width / 2, m_rect.Height / 2);
}
public void Updateme(MouseState ms_curr)
{
m_rect.X = ms_curr.X;
m_rect.Y = ms_curr.Y;
// Extra Task 1 Crosshair Red When Clicked
#region Extra task1
if (ms_curr.LeftButton == ButtonState.Pressed)
{
m_tint = Color.Red;
}
else
{
m_tint = Color.Green;
}
#endregion Extra task1
// Extra Task 2 Rotating Crosshair
#region Extra task2
#endregion Extra task2
// Extra Task 3 Crosshair Screenbounds
#region Extra task3
if (m_rect.X > 800)
{
m_rect.X = 800;
}
if (m_rect.X < 0)
{
m_rect.X = 0;
}
if (m_rect.Y > 480)
{
m_rect.Y = 480;
}
if (m_rect.Y < 0)
{
m_rect.Y = 0;
}
#endregion Extra task3
}
public override void drawme(SpriteBatch sBatch)
{
sBatch.Draw(m_txr, m_rect, null, m_tint, 0, m_center, SpriteEffects.None, 0);
}
}
class PlayerShip : MotionGraphic
{
public PlayerShip(Rectangle rect, Texture2D txrShip)
: base(rect, txrShip)
{
}
public void Updateme(KeyboardState kb, GameTime gt)
{
m_velocity = Vector2.Zero;
if (kb.IsKeyDown(Keys.W))
m_velocity.Y = -1;
if (kb.IsKeyDown(Keys.S))
m_velocity.Y = 1;
if (kb.IsKeyDown(Keys.A))
m_velocity.X = -1;
if (kb.IsKeyDown(Keys.D))
m_velocity.X = 1;
m_position += m_velocity;
// Extra Task 1 PlayerShip Screenbounds
#region Extra task1
if (m_rect.X > 800)
{
m_rect.X = 800;
}
if (m_rect.X < 0)
{
m_rect.X = 0;
}
if (m_rect.Y > 480)
{
m_rect.Y = 480;
}
if (m_rect.Y < 0)
{
m_rect.Y = 0;
}
#endregion Extra task1
}
}
}