【发布时间】:2021-04-12 00:16:11
【问题描述】:
过去几天我一直在使用 MonoGame 和 C# 对球进行物理模拟。球在重力作用下弹跳得很好,但是当球的弹跳太低时,球就会掉到地板上。有什么办法可以阻止这种情况发生吗? 我已经尝试过降低重力常数,改变碰撞的工作方式等,但似乎没有任何效果。 (我对使用图形还很陌生,所以简单的解释会很有帮助)
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace Particle_Simulation
{
public class Game1 : Game
{
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
Texture2D particleTexture;
SpriteFont font;
Rectangle particle;
Vector2 velocity = new Vector2(4, 0);
Vector2 acceleration = new Vector2(0, 0.25f);
public Game1()
{
graphics = new GraphicsDeviceManager(this);
//graphics.PreferredBackBufferWidth = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width;
//graphics.PreferredBackBufferHeight = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height;
Content.RootDirectory = "Content";
}
protected override void Initialize()
{
// TODO: Add your initialization logic here
base.Initialize();
}
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
//Load your game content here
particleTexture = Content.Load<Texture2D>("ball");
font = Content.Load<SpriteFont>("textFont");
particle = new Rectangle(200, 200, 60, 60);
}
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
Exit();
//Add your update logic here
velocity.X += acceleration.X;
velocity.Y += acceleration.Y;
particle.X += (int)velocity.X;
particle.Y += (int)velocity.Y;
if (particle.Top <= 0 || particle.Bottom >= GraphicsDevice.Viewport.Height)
velocity.Y = -velocity.Y;
if (particle.Left <= 0 || particle.Right >= GraphicsDevice.Viewport.Width)
velocity.X = -velocity.X;
base.Update(gameTime);
}
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
//Add your drawing code here
spriteBatch.Begin();
spriteBatch.Draw(particleTexture, particle, Color.White);
spriteBatch.DrawString(font, "X: " + velocity.X.ToString() + " Y: " + velocity.Y.ToString(), new Vector2(0, 0), Color.White);
spriteBatch.End();
base.Draw(gameTime);
}
}
}
【问题讨论】:
-
您的帖子中没有足够的信息确切地了解为什么碰撞不会阻止物体穿过地板。但是,重复的帖子中很好地描述了几种不同的可能性。如果您在查看这些内容后仍然遇到问题,请发布一个新问题,其中您提供了一个很好的 minimal reproducible example 和更详细的问题说明、到目前为止您尝试解决的问题以及具体 i> 你需要帮助。
-
@PeterDuniho 我已经查看了其他问题,但它们似乎正在处理 Unity 中预先构建的碰撞项目。这些和这个问题之间的区别在于我正在创建自己的碰撞检测,而不是使用 Unity 的内置碰撞。
-
“我正在创建自己的碰撞检测,而不是使用 Unity 的内置碰撞”——嗯,首先要改变的是,不要那样做。您正在使用具有精细物理引擎和碰撞检测系统的平台。它至少和你要实现的任何东西一样有效。或者,做与 Unity3d 相同的事情并为您的物理使用固定更新(实际上至少在其中一个副本中对此进行了解释)。