C# XNA-如何使敌人的精灵在碰撞时消失
在我的XNA游戏中,当我的鲨鱼撞到我的精灵时,精灵会移到屏幕边缘,而不是完全消失,无论我在它们碰撞时的距离是多少,精灵都会移到屏幕边缘 以下是我的更新游戏方法中的交叉点代码: foreach(雪碧crew1船员) 这是我的精灵课:C# XNA-如何使敌人的精灵在碰撞时消失,c#,xna,C#,Xna,在我的XNA游戏中,当我的鲨鱼撞到我的精灵时,精灵会移到屏幕边缘,而不是完全消失,无论我在它们碰撞时的距离是多少,精灵都会移到屏幕边缘 以下是我的更新游戏方法中的交叉点代码: foreach(雪碧crew1船员) 这是我的精灵课: using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio;
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 PickUpTheCrewGame
{
class Sprite
{
public Vector2 location;
public Vector2 velocity;//this hold the sprite movement
public Texture2D image;
public Rectangle bounds;//inventing the boundaries using rectange variable
public Color col = Color.White;
int maxVel = 600;
public Sprite(Vector2 location, Texture2D image, Color clr)
{
this.location = location;
this.image = image;
this.col = clr;
//----setting the boundaries of the screen to match the window-----
bounds = new Rectangle((int)location.X, (int)location.Y, 64, 64);
}
public Sprite(Vector2 location, Texture2D image)
{
this.location = location;
this.image = image;
//----setting the boundaries of the screen to match the window-----
bounds = new Rectangle((int)location.X, (int)location.Y, 64, 64);
}
public Sprite(Vector2 location,Vector2 vel, Texture2D image, Color clr)
{
this.location = location;
this.velocity = vel;
this.image = image;
this.col = clr;
//----setting the boundaries of the screen to match the window-----
bounds = new Rectangle((int)location.X, (int)location.Y, 64, 64);
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(image, location, col);
}
/// <summary>
/// Update method, anything attributes which need to be
/// assigneed to the sprites are here
/// </summary>
/// <param name="elapsed"></param>
public void Update(float elapsed)
{
//----sets the speed for the players----
location += velocity * elapsed;
//-------initialising the boundaries for the screen-----
bounds.X = (int)location.X;
bounds.Y = (int)location.Y;
//--------Posotive velocity---------
if (velocity.X > maxVel)
velocity.X = maxVel;
if (velocity.Y > maxVel)
velocity.Y = maxVel;
//----Negative velocity-------
if (velocity.X < -maxVel)
velocity.X = -maxVel;
if (velocity.Y < -maxVel)
velocity.Y = -maxVel;
//------adding friction to the AI------
velocity = velocity * 0.9f;
//-------Assigning the boundaries-----
if (bounds.Left < 0)
location.X = 0;
if (bounds.Top < 0)
location.Y = 0;
if (bounds.Right > 1280)
location.X = 1280 - bounds.Width;
if (bounds.Bottom > 720)
location.Y = 720 - bounds.Height;
}
public void Accelerate(Vector2 direction)
{
//-----normalises is to get a unit vector (40 is force), normal is direction
velocity += 20 * Vector2.Normalize(direction);
}
}
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用Microsoft.Xna.Framework;
使用Microsoft.Xna.Framework.Audio;
使用Microsoft.Xna.Framework.Content;
使用Microsoft.Xna.Framework.GamerServices;
使用Microsoft.Xna.Framework.Graphics;
使用Microsoft.Xna.Framework.Input;
使用Microsoft.Xna.Framework.Media;
名称空间拾音器游戏
{
雪碧
{
公共矢量2位置;
公共向量2 velocity;//这保持了精灵的运动
公共纹理2D图像;
公共矩形边界;//使用rectange变量创建边界
公共颜色col=颜色。白色;
int maxVel=600;
公共精灵(矢量2位置、纹理2D图像、彩色clr)
{
这个位置=位置;
这个图像=图像;
this.col=clr;
//----设置屏幕边界以匹配窗口-----
边界=新矩形((int)location.X,(int)location.Y,64,64);
}
公共精灵(矢量2位置,纹理2D图像)
{
这个位置=位置;
这个图像=图像;
//----设置屏幕边界以匹配窗口-----
边界=新矩形((int)location.X,(int)location.Y,64,64);
}
公共精灵(矢量2位置、矢量2级别、纹理2D图像、彩色clr)
{
这个位置=位置;
这个速度=水平;
这个图像=图像;
this.col=clr;
//----设置屏幕边界以匹配窗口-----
边界=新矩形((int)location.X,(int)location.Y,64,64);
}
公共作废抽签(SpriteBatch SpriteBatch)
{
spriteBatch.Draw(图像、位置、颜色);
}
///
///更新方法,任何需要更新的属性
///分配给精灵的人在这里
///
///
公共无效更新(浮动已过)
{
//----为玩家设定速度----
位置+=速度*经过;
//-------初始化屏幕的边界-----
bounds.X=(int)location.X;
bounds.Y=(int)location.Y;
//--------正运动速度---------
如果(速度.X>maxVel)
速度X=最大值;
如果(速度Y>最大值)
速度Y=最大值;
//----负速度-------
如果(速度.X<-maxVel)
速度X=-maxVel;
if(速度Y<-maxVel)
速度Y=-maxVel;
//------给人工智能增加摩擦------
速度=速度*0.9f;
//-------分配边界-----
if(bounds.Left<0)
位置X=0;
if(bounds.Top<0)
位置Y=0;
如果(bounds.Right>1280)
location.X=1280-bounds.Width;
如果(bounds.Bottom>720)
位置Y=720——边界高度;
}
公共空间加速(矢量2方向)
{
//-----法线化是得到一个单位向量(40是力),法线是方向
速度+=20*矢量2.归一化(方向);
}
}
}
以下是我的全部(main.cs)代码:
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用Microsoft.Xna.Framework;
使用Microsoft.Xna.Framework.Audio;
使用Microsoft.Xna.Framework.Content;
使用Microsoft.Xna.Framework.GamerServices;
使用Microsoft.Xna.Framework.Graphics;
使用Microsoft.Xna.Framework.Input;
使用Microsoft.Xna.Framework.Media;
使用System.IO;
使用系统文本;
名称空间拾音器游戏
{
///
///这是游戏的主要类型
///
公共类PickUpTheCrewGame:Microsoft.Xna.Framework.Game
{
//枚举的状态
公共枚举状态
{
菜单,
玩,
加梅奥弗,
}
//设置变量
图形管理器图形;
SpriteBatch SpriteBatch;
SpriteFont消息字体;
SpriteFont播放器Corefont;
纹理2D背景纹理;
矩形背景矩形;
纹理2D图像纹理;
矩形菜单菜单矩形;
纹理2D图像纹理;
矩形或矩形;
雪碧蓝球;
雪碧绿球;
雪碧橙球;
雪碧弹珠;
雪碧红球;
雪碧c;
雪碧黄球;
公共纹理2D菜单图像;
公众形象;
//---球员记分员
int playerScore=0;
int高分=0;
//列表
列表鲨鱼=新列表();
List crew=新列表();
List highscoreList=新列表();
//第一状态
状态gameState=State.Menu;
HUD HUD=新HUD();
///
///PickUpTheCrew游戏的构造函数
///
公共皮卡车游戏()
{
graphics=新的GraphicsDeviceManager(此);
Content.RootDirectory=“Content”;
//sreen尺寸
graphics.PreferredBackBufferWidth=1280;
graphics.PreferredBackBufferHeight=720;
menuImage=null;
gameoverImage=null;
}
///
///允许游戏在开始运行之前执行任何需要的初始化。
///这是
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 PickUpTheCrewGame
{
class Sprite
{
public Vector2 location;
public Vector2 velocity;//this hold the sprite movement
public Texture2D image;
public Rectangle bounds;//inventing the boundaries using rectange variable
public Color col = Color.White;
int maxVel = 600;
public Sprite(Vector2 location, Texture2D image, Color clr)
{
this.location = location;
this.image = image;
this.col = clr;
//----setting the boundaries of the screen to match the window-----
bounds = new Rectangle((int)location.X, (int)location.Y, 64, 64);
}
public Sprite(Vector2 location, Texture2D image)
{
this.location = location;
this.image = image;
//----setting the boundaries of the screen to match the window-----
bounds = new Rectangle((int)location.X, (int)location.Y, 64, 64);
}
public Sprite(Vector2 location,Vector2 vel, Texture2D image, Color clr)
{
this.location = location;
this.velocity = vel;
this.image = image;
this.col = clr;
//----setting the boundaries of the screen to match the window-----
bounds = new Rectangle((int)location.X, (int)location.Y, 64, 64);
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(image, location, col);
}
/// <summary>
/// Update method, anything attributes which need to be
/// assigneed to the sprites are here
/// </summary>
/// <param name="elapsed"></param>
public void Update(float elapsed)
{
//----sets the speed for the players----
location += velocity * elapsed;
//-------initialising the boundaries for the screen-----
bounds.X = (int)location.X;
bounds.Y = (int)location.Y;
//--------Posotive velocity---------
if (velocity.X > maxVel)
velocity.X = maxVel;
if (velocity.Y > maxVel)
velocity.Y = maxVel;
//----Negative velocity-------
if (velocity.X < -maxVel)
velocity.X = -maxVel;
if (velocity.Y < -maxVel)
velocity.Y = -maxVel;
//------adding friction to the AI------
velocity = velocity * 0.9f;
//-------Assigning the boundaries-----
if (bounds.Left < 0)
location.X = 0;
if (bounds.Top < 0)
location.Y = 0;
if (bounds.Right > 1280)
location.X = 1280 - bounds.Width;
if (bounds.Bottom > 720)
location.Y = 720 - bounds.Height;
}
public void Accelerate(Vector2 direction)
{
//-----normalises is to get a unit vector (40 is force), normal is direction
velocity += 20 * Vector2.Normalize(direction);
}
}
}
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 System.IO;
using System.Text;
namespace PickUpTheCrewGame
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class PickUpTheCrewGame : Microsoft.Xna.Framework.Game
{
// states for the enums
public enum State
{
Menu,
Playing,
Gameover,
}
//Setting the variables
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
SpriteFont messageFont;
SpriteFont playerScoreFont;
Texture2D backgroundTexture;
Rectangle backgroundRectangle;
Texture2D menuImageTexture;
Rectangle menuImageRectange;
Texture2D gameoverImageTexture;
Rectangle gameoverImageRectangle;
Sprite BlueBall;
Sprite GreenBall;
Sprite OrangeBall;
Sprite PinkBall;
Sprite RedBall;
Sprite c;
Sprite YellowBall;
public Texture2D menuImage;
public Texture2D gameoverImage;
//---player scoresyer
int playerScore = 0;
int highScore = 0;
//Lists
List<sharks> sharks = new List<sharks>();
List<Sprite> crew = new List<Sprite>();
List<int> highscoreList = new List<int>();
//Set First State
State gameState = State.Menu;
HUD hud = new HUD();
/// <summary>
/// Constructor for the PickUpTheCrew Game
/// </summary>
public PickUpTheCrewGame()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
//sreen size
graphics.PreferredBackBufferWidth = 1280;
graphics.PreferredBackBufferHeight = 720;
menuImage = null;
gameoverImage = null;
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// TODO: Add your initialization logic here
//enable the mousepointer
//IsMouseVisible = true;
base.Initialize();
}
/// <summary>
/// Highscore method
/// </summary>
/// <returns></returns>
public bool IsHighScore()
{
if (playerScore > hud.highScore)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// Writing the Save File
/// </summary>
/// <param name="filename"></param>
public void Save(string filename)
{
System.IO.TextWriter textOut = null;
try
{
textOut = new System.IO.StreamWriter(filename);
Save(textOut);
}
catch (Exception e)
{
throw e;
}
finally
{
if (textOut != null) textOut.Close();
}
}
/// <summary>
/// Saving the information into the save file
/// </summary>
/// <param name="textOut"></param>
private void Save(TextWriter textOut)
{
try
{
foreach (Sprite crew1 in crew)
{
textOut.WriteLine(crew1.location.X);
textOut.WriteLine(crew1.location.Y);
}
foreach (sharks enemySprite in sharks)
{
//textOut.WriteLine("Shark");
textOut.WriteLine(enemySprite.location.X);
textOut.WriteLine(enemySprite.location.Y);
}
}
catch
{
}
}
/// <summary>
/// This method loads the file from save document
/// </summary>
/// <param name="filename"></param>
public void Load(string filename)
{
System.IO.TextReader textIn = null;
//try
//{
textIn = new System.IO.StreamReader(filename);
Load(textIn);
//}
//catch (Exception e)
//{
// throw e;
//}
//finally
//{
if (textIn != null) textIn.Close();
//}
}
/// <summary>
/// Load method for the data in the file
/// </summary>
/// <param name="textIn"></param>
private void Load(TextReader textIn)
{
foreach (Sprite crew1 in crew)
{
crew1.location.X = float.Parse(textIn.ReadLine());
crew1.location.Y = float.Parse(textIn.ReadLine());
}
foreach (sharks enemySprite in sharks)
{
enemySprite.location.X = float.Parse(textIn.ReadLine());
enemySprite.location.Y = float.Parse(textIn.ReadLine());
}
//throw new NotImplementedException();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
hud.LoadContent(Content);
//-----LOAD THE MENU BACKGROUND-----
menuImageTexture = Content.Load<Texture2D>("menuImage");
menuImageRectange = new Rectangle(0, 0,
Window.ClientBounds.Width,
Window.ClientBounds.Height);
//------LOAD INGAME BACKGROUND-----
backgroundTexture = Content.Load<Texture2D>("Background");
backgroundRectangle = new Rectangle(
0, 0, // top left hand corner
Window.ClientBounds.Width,
Window.ClientBounds.Height); // size of screen display
//GAMEOVER IMAGE BACKGROUND
gameoverImageTexture = Content.Load<Texture2D>("gameoverImage");
gameoverImageRectangle = new Rectangle(
0, 0,
Window.ClientBounds.Width,
Window.ClientBounds.Height);
//------- Loading in Captains crew-------
c = new Sprite(new Vector2(400, 150), new Vector2(400, 150),
Content.Load<Texture2D>("WhiteBall"), Color.White);
BlueBall = new Sprite(new Vector2(640, 450),
Content.Load<Texture2D>("BlueBall"));
crew.Add(BlueBall);
GreenBall = new Sprite(new Vector2(750, 200),
Content.Load<Texture2D>("GreenBall"));
crew.Add(GreenBall);
OrangeBall = new Sprite(new Vector2(115, 400),
Content.Load<Texture2D>("OrangeBall"));
crew.Add(OrangeBall);
RedBall = new Sprite(new Vector2(500, 600),
Content.Load<Texture2D>("RedBall"));
crew.Add(RedBall);
YellowBall = new Sprite(new Vector2(800, 400),
Content.Load<Texture2D>("YellowBall"));
crew.Add(YellowBall);
PinkBall = new Sprite(new Vector2(25, 175),
Content.Load<Texture2D>("PinkBall"));
crew.Add(PinkBall);
//--------Loading in the Sharks------
sharks s = new sharks(new Vector2(1100, 50),
Content.Load<Texture2D>("BlackBall"));
sharks.Add(s);
s = new sharks(new Vector2(950, 170),
Content.Load<Texture2D>("BlackBall"));
sharks.Add(s);
s = new sharks(new Vector2(300, 350),
Content.Load<Texture2D>("BlackBall"));
sharks.Add(s);
messageFont = Content.Load<SpriteFont>("messageFont");
// TODO: use this.Content to load your game content here
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
//----------This gets the time value---------
float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
//--------------keyboard input---------------
//Exit
if (Keyboard.GetState().IsKeyDown(Keys.Escape))
this.Exit();
//Save
if (Keyboard.GetState().IsKeyDown(Keys.S))
Save("test.txt");
//Load
if (Keyboard.GetState().IsKeyDown(Keys.L))
Load("test.txt");
//Directional Movement
if (Keyboard.GetState().IsKeyDown(Keys.Left))
c.velocity.X = -350;
if (Keyboard.GetState().IsKeyDown(Keys.Right))
c.velocity.X = 350;
if (Keyboard.GetState().IsKeyDown(Keys.Down))
c.velocity.Y = 350;
if (Keyboard.GetState().IsKeyDown(Keys.Up))
c.velocity.Y = -350;
//UPDATING PLAYING STATE
switch (gameState)
{
case State.Playing:
c.Update(elapsed);
foreach (Sprite cr in crew)
{
cr.Update(elapsed);
}
c.col = Color.White;
//----sharks intersects with whiteball----
foreach (sharks s in sharks)
{
if (c.bounds.Intersects(s.bounds))
{
gameState = State.Gameover;
break;
}
}
foreach (sharks s in sharks)
{
s.Update(elapsed, c.location);
}
hud.Update(gameTime);
//----sprites intersect with whiteball----
foreach (Sprite crew1 in crew)
{
if (c.bounds.Intersects(crew1.bounds))
{
//gameState = State.Gameover;
playerScore += 1;
crew1.bounds.X = 1000000;
crew1.bounds.Y = 1000000;
crew1.location.Y = 1000000;
crew1.location.X = 1000000;
break;
}
} break;
//UPDATING MENU STATE
case State.Menu:
{
//Get keyboard state
KeyboardState keyState = Keyboard.GetState();
if (keyState.IsKeyDown(Keys.Enter))
{
gameState = State.Playing;
}
break;
}
//UPDATING GAMEOVER STATE
case State.Gameover:
{
//Get keyboard state
KeyboardState keyState = Keyboard.GetState();
if (keyState.IsKeyDown(Keys.Back))
{
if (IsHighScore())
{
hud.highScore = playerScore;
SavehighScore("highScore.txt");
}
//resetting the everything to clear after gameover
sharks.Clear();
crew.Clear();
playerScore = 0;
//This redraws the sprites positions after gamover and the scren cleared and everything is resetted
c = new Sprite(new Vector2(400, 150), new Vector2(400, 150),
Content.Load<Texture2D>("WhiteBall"), Color.White);
BlueBall = new Sprite(new Vector2(640, 450),
Content.Load<Texture2D>("BlueBall"));
crew.Add(BlueBall);
GreenBall = new Sprite(new Vector2(750, 200),
Content.Load<Texture2D>("GreenBall"));
crew.Add(GreenBall);
OrangeBall = new Sprite(new Vector2(115, 400),
Content.Load<Texture2D>("OrangeBall"));
crew.Add(OrangeBall);
RedBall = new Sprite(new Vector2(500, 600),
Content.Load<Texture2D>("RedBall"));
crew.Add(RedBall);
YellowBall = new Sprite(new Vector2(800, 400),
Content.Load<Texture2D>("YellowBall"));
crew.Add(YellowBall);
PinkBall = new Sprite(new Vector2(25, 175),
Content.Load<Texture2D>("PinkBall"));
crew.Add(PinkBall);
//--------Loading in the Sharks------
sharks s = new sharks(new Vector2(1100, 50),
Content.Load<Texture2D>("BlackBall"));
sharks.Add(s);
s = new sharks(new Vector2(950, 170),
Content.Load<Texture2D>("BlackBall"));
sharks.Add(s);
s = new sharks(new Vector2(300, 350),
Content.Load<Texture2D>("BlackBall"));
sharks.Add(s);
gameState = State.Menu;
}
break;
}
}
base.Update(gameTime);
}
/// <summary>
/// This makes the highscore file
/// </summary>
/// <param name="filename"></param>
private void SavehighScore(string filename)
{
TextWriter textOut = null;
try
{
if (File.Exists(filename))
File.Delete(filename);
textOut = new StreamWriter(filename);
textOut.WriteLine(hud.highScore);
}
catch (Exception e)
{
throw e;
}
finally
{
if (textOut != null) textOut.Close();
}
//throw new NotImplementedException();
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
switch (gameState)
{
//DRAWING PLAYING STATE
case State.Playing:
{
spriteBatch.Draw(backgroundTexture, backgroundRectangle,
Color.White);
c.Draw(spriteBatch);
//FOR EACH CREW DRAW
foreach (Sprite cr in crew)
{
cr.Draw(spriteBatch);
}
//FOREACH SHARK DRAW
foreach (sharks s in sharks)
{
s.Draw(spriteBatch);
}
hud.Draw(spriteBatch);
spriteBatch.DrawString(messageFont, playerScore.ToString(),
new Vector2(200, 0),
Color.White);
//spriteBatch.DrawString(messageFont, highScore.ToString(),
// new Vector2(200, 100), Color.White);
spriteBatch.DrawString(messageFont, " Player Scores - ",
new Vector2(0, 0), Color.White);
break;
//spriteBatch.DrawString(messageFont, " High Score - ",
//new Vector2(200, 200), Color.White);
//break;
}
//DRAWING MENU STATE
case State.Menu:
{
spriteBatch.Draw(menuImageTexture, menuImageRectange, Color.White);
break;
}
//DRAWING GAMEOVER STATE
case State.Gameover:
{
spriteBatch.Draw(gameoverImageTexture, gameoverImageRectangle, Color.White);
spriteBatch.DrawString(messageFont, "Your Final Score was - " + playerScore.ToString(), new Vector2(0, 0), Color.White);
spriteBatch.DrawString(messageFont, "Your High score - " + hud.highScore.ToString(), new Vector2(0, 100), Color.White);
break;
}
}
spriteBatch.End();
base.Draw(gameTime);
}
}
}