C# 当精灵与AI保持一定距离时,如何让AI跟随精灵
我在这里尝试实现的目标是,当白球(精灵)在一定距离内走向黑球(AI)时,黑球将跟随白球 我已经这样做了,人工智能自动走向精灵,但我不知道当只有精灵在一定距离内时该怎么做 主要游戏类 这是主要的游戏课C# 当精灵与AI保持一定距离时,如何让AI跟随精灵,c#,xna,C#,Xna,我在这里尝试实现的目标是,当白球(精灵)在一定距离内走向黑球(AI)时,黑球将跟随白球 我已经这样做了,人工智能自动走向精灵,但我不知道当只有精灵在一定距离内时该怎么做 主要游戏类 这是主要的游戏课 using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft
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;
namespace PickUpTheCrewGame
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class PickUpTheCrewGame : Microsoft.Xna.Framework.Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
SpriteFont messageFont;
Texture2D backgroundTexture;
Rectangle backgroundRectangle;
Sprite BlueBall;
Sprite GreenBall;
Sprite OrangeBall;
Sprite PinkBall;
Sprite RedBall;
Sprite c;
Sprite YellowBall;
//---player scores
int playerScore = 0;
//List<Sprite> sprite = new List<Sprite>();
List<sharks> sharks = new List<sharks>();
List<Sprite> crew = new List<Sprite>();
//Sprite Background;
public PickUpTheCrewGame()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
//sreen size
graphics.PreferredBackBufferWidth = 1280;
graphics.PreferredBackBufferHeight = 720;
}
/// <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();
}
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();
}
}
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
{
}
}
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();
//}
}
private void Load(TextReader textIn)
{
foreach (Sprite crew1 in crew)
{
crew1.location.X = int.Parse(textIn.ReadLine());
crew1.location.Y = int.Parse(textIn.ReadLine());
}
foreach (sharks enemySprite in sharks)
{
enemySprite.location.X = int.Parse(textIn.ReadLine());
enemySprite.location.Y = int.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);
backgroundTexture = Content.Load<Texture2D>("Background");
backgroundRectangle = new Rectangle(
0, 0, // top left hand corner
Window.ClientBounds.Width,
Window.ClientBounds.Height); // size of screen display
//-------Captains crew-------
c = new Sprite(new Vector2(0, 0), new Vector2(0, 0),
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(250, 600),
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);
//--------Sharks------
sharks s = new sharks(new Vector2(1000, 200),
Content.Load<Texture2D>("BlackBall"));
sharks.Add(s);
s = new sharks(new Vector2(900, 200),
Content.Load<Texture2D>("BlackBall"));
sharks.Add(s);
s = new sharks(new Vector2(800, 200),
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 `enter code here`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.Back))
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;
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))
{
c.col = Color.Red;
break;
}
}
foreach (sharks s in sharks)
{
s.Update(elapsed, c.location);
}
//----sprites intersect with whiteball----
foreach (Sprite crew1 in crew)
{
if (c.bounds.Intersects(crew1.bounds))
{
c.col = Color.Red;
playerScore += 1;
crew1.bounds.X = 10000;
crew1.bounds.Y = 10000;
crew1.location.Y = 10000;
crew1.location.X = 10000;
break;
}
}
base.Update(gameTime);
}
/// <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();
spriteBatch.Draw(backgroundTexture, backgroundRectangle,
Color.White);
//Background.Draw(spriteBatch);
c.Draw(spriteBatch);
foreach (Sprite cr in crew)
{
cr.Draw(spriteBatch);
}
foreach (sharks s in sharks)
{
s.Draw(spriteBatch);
}
//---------messsage font succussfully saved----------
spriteBatch.DrawString(messageFont, playerScore.ToString(),
new Vector2(145, 0),
Color.White);
spriteBatch.DrawString(messageFont, " Player Scores",
new Vector2(0, 0), Color.White);
spriteBatch.End();
base.Draw(gameTime);
}
}
}
可以通过减去白球和黑球的位置向量来检查它们之间的距离。这将为您提供一个向量,表示两个球之间的“间隙” 你已经这样做了(当你调用Accelerate时)来获得方向。如果你想知道距离,只需要通过减法得到向量2的长度:它实际上是两个球之间的距离 在这个距离上设置一个条件(在我的例子中是SharkVision),只有当距离小于SharkVision时,你的鲨鱼才会移动。调整SharkVision以获得最适合您的效果
class sharks:Sprite
{
public const float SharkVision = 500f;
...
public void Update(float elapsed, Vector2 playerLoc)
{
if ((playerLoc - location).Length() < SharkVision)
Accelerate(playerLoc - location);
base.Update(elapsed);
}
}
鲨鱼类:精灵
{
公共常数浮动SharkVision=500f;
...
公共无效更新(浮动已过,矢量2 playerLoc)
{
if((playerLoc-location).Length()
用模式演示
在这幅图中,“a”是白球位置的向量,“b”是黑球位置的向量。
如果减去它们,则得到向量“a-b”。它的长度等于两个球之间的距离,它的方向给了你移动的方向
警告:减法的方向可以反转移动的方向。总是这样:
destinationLocation-startLocation
呃,我不确定,我以为我的AI类就是我的AI,我在Sprite类中设置了一些,这也是我的错误。我已经更新了您的问题,以显示各个列表。最后我没有看到你的AI课程。:)不用担心,我已经尝试过搜索它并尝试过了,但没有得到任何运气,为什么我希望有人能潜在地帮助我,而且我对堆栈溢出非常陌生:)我编辑过你的标题。请看“”,其中的共识是“不,他们不应该”。嗨,谢谢你的反馈。在将其添加到我的代码中之后,我收到一条错误消息“运算符‘我的错误’:长度是一种方法。添加括号。我修好了我的帖子。请问我该怎么处理括号呢。谢谢你的回复:)鲨鱼在一定距离内似乎根本不会醒来,我已经将浮点数改为一个更高的数字,但没有区别,谢谢你再次输入一个更高的值。这是我的错误:在这种情况下,2.5真的很低,因为它说玩家需要距离鲨鱼2.5像素。换500元。我又把我的帖子修好了。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
namespace PickUpTheCrewGame
{
class sharks:Sprite
{
public sharks(Vector2 location, Texture2D image)
:base(location,image)
{
}
public void Update(float elapsed, Vector2 playerLoc)
{
Accelerate(playerLoc - location);//should make the ai go towards the player all the time
base.Update(elapsed);
}
}
}
class sharks:Sprite
{
public const float SharkVision = 500f;
...
public void Update(float elapsed, Vector2 playerLoc)
{
if ((playerLoc - location).Length() < SharkVision)
Accelerate(playerLoc - location);
base.Update(elapsed);
}
}