XNA - 傍克隆 - 反思球时撞到墙? [英] XNA - Pong Clone - Reflecting ball when it hits a wall?
问题描述
我试图让球反弹了我的用户界面的顶部和底部的'墙'创建2D傍克隆时的感觉。
这是我的Game.cs
I'm trying to make the ball bounce off of the top and bottom 'Walls' of my UI when creating a 2D Pong Clone. This is my Game.cs
public void CheckBallPosition()
{
if (ball.Position.Y == 0 || ball.Position.Y >= graphics.PreferredBackBufferHeight)
ball.Move(true);
else
ball.Move(false);
if (ball.Position.X < 0 || ball.Position.X >= graphics.PreferredBackBufferWidth)
ball.Reset();
}
目前,我在我的Ball.cs
At the moment I'm using this in my Ball.cs
public void Move(bool IsCollidingWithWall)
{
if (IsCollidingWithWall)
{
Vector2 normal = new Vector2(0, 1);
Direction = Vector2.Reflect(Direction,normal);
this.Position += Direction;
Console.WriteLine("WALL COLLISION");
}
else
this.Position += Direction;
}
它的工作原理,但我使用的是手动输入正常和我想知道如何计算正常屏幕?
推荐答案
好了,这是我将如何处理它
Well, this is how I would handle it
public void CheckBallPositionAndMove()
{
if (ball.Position.Y <= 0 || ball.Position.Y >= graphics.PreferredBackBufferHeight)
ball.HandleWallCollision();
ball.Move();
if (ball.Position.X < 0 || ball.Position.X >= graphics.PreferredBackBufferWidth)
ball.Reset();
}
//In Ball.cs:
private void HandleWallCollision(Vector2 normal)
{
Direction.Y *= -1; //Reflection about either normal is the same as multiplying y-vector by -1
}
private void Move()
{
this.Position += Direction;
}
然而,使用这种
请注意离散碰撞检测,你等到球已经移过顶后/屏幕下方来检测碰撞; 发生帧之间的碰撞可能是noticably关,尤其是当球快速移动。这是尤其的一个问题,如果你正在使用这种碰撞检测方法检测碰撞桨,因为如果球移动速度不够快,这是可能的球通过桨向右移动!
Note however that using this "discrete" collision detection, you wait until after the ball has moved past the top/bottom of the screen to detect a collision; collisions that occur "between" frames may be noticably off, especially if the ball is moving fast. This is especially a problem if you are using this collision-detection method to detect collision with a paddle, since, if the ball is moving fast enough, it is possible for the ball to move right through the paddle!
对这个问题的解决方法是使用了被称为连续碰撞检测。 CCD通常比显著离散的碰撞检测更加复杂;幸运的是,乒乓球是很简单的,这样做CCD只会稍微复杂一些。不过,你仍然会需要高中代数扎实抓好以求解方程。
The solution to this problem is to use what is known as Continuous Collision Detection. CCD is usually significantly more complex than discrete collision detection; fortunately, pong is simple enough that doing CCD would only be slightly more complex. However, you'd still need a solid grasp of high-school algebra to solve the equations.
如果你仍然有兴趣,有CCD的一个很好的解释在< A HREF =http://www.cs.unc.edu/%7Elin/COMP259-S05/LEC/14.ppt相对=nofollow>这个讲座和的这个GameDev文章去多一点深入。也有许多的问题与它左右。
If you are still interested, there is a good explaination of CCD in this lecture, and this GameDev article goes a bit more in-depth. There are also many questions relating to it on SO.
这篇关于XNA - 傍克隆 - 反思球时撞到墙?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!