Monogame碰撞检测无法正常工作

问题描述 投票:0回答:1

所以我正在尝试使用monogame创建一个乒乓球游戏,我的命中检测有一些问题。我希望球在击中左侧桨时切换方向,但由于某种原因,只能在顶部检测到碰撞,而不是侧面,因此球只是穿过桨的两侧但是在击中顶部时弹跳可以让任何人看到我究竟做错了什么?继承我的代码

蝙蝠类的一部分

public class Bat : DrawableGameComponent
{
    private SpriteBatch spriteBatch;
    private Texture2D tex;
    private Vector2 speed;
    private Vector2 position;
    private Vector2 stage;
    public Rectangle Rectangle
    {
        get
        {
            return new Rectangle((int)position.X, (int)position.Y, tex.Width, tex.Height);
        }
    }

    public Bat(Game game,
        SpriteBatch spriteBatch,
        Texture2D tex,
        Vector2 position,
        Vector2 speed,
        Vector2 stage): base(game)
    {
        this.spriteBatch = spriteBatch;
        this.tex = tex;
        this.position = position;
        this.speed = speed;
        this.stage = stage;
    }

Collision类更新方法

public override void Update(GameTime gameTime)
{
    if (ball.Rectangle.Intersects(bat.Rectangle))
    {

        ball.speed.Y = -Math.Abs(ball.speed.Y);
        hitSound.Play();
    }

    base.Update(gameTime);
}

以及添加蝙蝠和碰撞检测的游戏类

Texture2D batTex = this.Content.Load<Texture2D>("Images/BatLeft");
Vector2 batPos = new Vector2(100,100);
Vector2 batSpeed = new Vector2(4, 0);
bat = new Bat(this, spriteBatch, batTex, batPos, batSpeed, stage);
this.Components.Add(bat);

SoundEffect dingSound = this.Content.Load<SoundEffect>("Music/ding");

CollisionDetection cd = new CollisionDetection(this, ball, bat, dingSound);
this.Components.Add(cd);
c# xna collision-detection collision monogame
1个回答
0
投票

每当球的矩形与球拍的矩形相交时,你就会反转球的速度方向。仅当与对象的顶部或底部发生碰撞时,此方法才能正常工作。

每当你的球碰撞桨的顶部时,它的矩形就会穿过桨的矩形。通过将球的当前向下速度反转到向上速度,您可以完全从球拍的矩形中移除球的矩形。

每当你的球与两侧碰撞时,球的速度就会变化 {0, ballspeed}{0, -ballSpeed} 这很可能不足以将球的矩形从桨的矩形中释放出来。如果它没有从矩形中释放,则下一次更新将再次反转方向,从而取消先前的更新。球将继续卡在矩形中,直到球拍移动。

要解决您的问题,您应该检查球是否影响了桨的顶部,侧面或底部。然后,相应地调整球的运动。

为了帮助您入门,我的旧碰撞检测方法就是一个例子:

// Moves and checks for collision on the Y-axis

position.Y += ball.speed.Y;
if (Hitbox().Intersects(obstacle))
{
    position.Y -= ball.speed.Y;
    ball.speed.Y = -ball.speed.Y;
}

// Moves and checks for collision on the X-axis

position.X += ball.speed.X;
if (Hitbox().Intersects(obstacle))
{
    position.X -= ball.speed.X;
    ball.speed.X = -ball.speed.X;
}

希望我能提供帮助。如果您对我的解释或代码有任何疑问,请随时提出。

-GHC

© www.soinside.com 2019 - 2024. All rights reserved.