两个矩形的相互作用
本文关键字:相互作用 两个 | 更新日期: 2023-09-27 18:21:07
我正在尝试查看两个独立对象的两个矩形是否相交。不幸的是,它不起作用。这是代码:
播放器
class Player
{
public static Texture2D texture;
public int xPos = 320;
public int yPos = 530;
public Rectangle rectangle;
public void Draw(SpriteBatch spriteBatch)
{
rectangle = new Rectangle(xPos, yPos, 75, 59);
spriteBatch.Draw(texture, rectangle, Color.White);
}
public void Update(GameTime gameTime)
{
KeyboardState keyboard = Keyboard.GetState();
if (keyboard.IsKeyDown(Keys.Left))
{
xPos -= 3;
}
if (keyboard.IsKeyDown(Keys.Right))
{
xPos += 3;
}
}
}
Asteriod
public class Asteroid : gameObject
{
int xPos = 0;
int yPos = -10;
public override void Draw(SpriteBatch spriteBatch)
{
rectangle = new Rectangle(xPos, yPos, 32, 32);
spriteBatch.Draw(texture, rectangle,Color.White);
}
public override void Update(GameTime gameTime)
{
yPos++;
rectangle = new Rectangle(xPos, yPos, 32, 32);
}
public Asteroid(int value)
{
xPos = value;
}
}
游戏对象
public abstract class gameObject
{
public static Texture2D texture;
public Rectangle rectangle;
public abstract void Draw(SpriteBatch spriteBatch);
public abstract void Update(GameTime gameTime);
}
游戏
public class Game1 : Microsoft.Xna.Framework.Game
{
List<gameObject> objectList = new List<gameObject>();
Random rand = new Random(1);
Asteroid asteroid;
int asteroidCount = 0;
Player player = new Player();
protected override void Update(GameTime gameTime)
{
scorevalue++;
player.Update(gameTime);
if (rand.Next(0, 8) == 2 && asteroidCount < 50)
{
for (int i = 0; i < 5; i++)
{
asteroid = new Asteroid(rand.Next(32,screenWidth));
objectList.Add(asteroid);
asteroidCount++;
}
}
foreach (Asteroid asteroid in objectList)
{
asteroid.Update(gameTime);
}
for (int i = 0; i < objectList.Count(); i++)
{
if (objectList[i].rectangle.Intersects(player.rectangle))
{
objectList.Remove(asteroid);
}
}
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();
// TODO: Add your update logic here
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
// TODO: Add your drawing code here
spriteBatch.Begin();
spriteBatch.DrawString(font, "Score: " + scorevalue, new Vector2(5, 5), Color.White);
foreach (Asteroid asteroid in objectList)
{
asteroid.Draw(spriteBatch);
}
player.Draw(spriteBatch);
spriteBatch.End();
base.Draw(gameTime);
}
}
我们非常感谢所有的帮助。当我试图循环通过并检查交叉点时,它不起作用。非常感谢。
你试过这个吗?
Rectangle rect = Rectangle.Intersect(rectangle1, rectangle2);
if (rect.IsEmpty)
{
}
似乎忘记更新Player类中的rectangle
。
public void Update(GameTime gameTime)
{
KeyboardState keyboard = Keyboard.GetState();
if (keyboard.IsKeyDown(Keys.Left))
{
xPos -= 3;
}
if (keyboard.IsKeyDown(Keys.Right))
{
xPos += 3;
}
rectangle.X = xPos;
}