【发布时间】:2023-01-17 19:36:20
【问题描述】:
我正在为我的 A Level 编程项目制作平台游戏,玩家在触摸平台时会自动跳到平台上。但是,我在碰撞检测方面遇到了麻烦,因为它只在一个平台上弹跳,然后直接从其余平台掉落。他们都有相同的标签,所以我知道这不是问题所在。
它的编码方式是它会检测与任何带有“平台”标签的矩形的碰撞,但它只检测与 1 个矩形的碰撞
下面的代码示例:
public partial class MainWindow : Window
{
private DispatcherTimer GameTimer = new DispatcherTimer();
private bool LeftKeyPressed, RightKeyPressed, gravity;
double score;
//this value will increase to be 5x the highest Y value so the score increases the higher Meke gets
private float SpeedX, SpeedY, FrictionX = 0.88f, Speed = 1, FrictionY = 0.80f;
//SpeedX controls horizontal movement, SpeedY controls vertical movement
private void Collide(string Dir)
{
foreach (var x in GameScreen.Children.OfType<Rectangle>())
{
if (x.Tag != null)
{
var platformID = (string)x.Tag;
if (platformID == "platform")
{
x.Stroke = Brushes.Black;
Rect MeekHB = new Rect(Canvas.GetLeft(Meek), Canvas.GetTop(Meek), Meek.Width, Meek.Height);
Rect PlatformHB = new Rect(Canvas.GetLeft(x), Canvas.GetTop(x), x.Width, x.Height);
int Jumpcount = 1;
if (MeekHB.IntersectsWith(PlatformHB))
{
if (Dir == "y")
{
while (Jumpcount != 700)
{
gravity = false;
Jumpcount = Jumpcount + 1;
}
}
}
else
{
gravity = true;
}
}
}
}
}
private void KeyboardUp(object sender, KeyEventArgs e)
{
//this is what detects when the 'A' key is being pressed
if (e.Key == Key.A)
{
LeftKeyPressed = false;
}
if (e.Key == Key.D)
{
RightKeyPressed = false;
}
}
private void KeyboardDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.A)
{
LeftKeyPressed = true;
}
if (e.Key == Key.D)
{
RightKeyPressed = true;
}
}
public MainWindow()
{
InitializeComponent();
GameScreen.Focus();
GameTimer.Interval = TimeSpan.FromMilliseconds(16);
GameTimer.Tick += GameTick;
GameTimer.Start();
}
private void GameTick(Object Sender, EventArgs e)
{
txtScore.Content = "Score: " + score;
if (LeftKeyPressed)
{
SpeedX -= Speed;
}
if (RightKeyPressed)
{
SpeedX += Speed;
}
if (gravity == true)
{
SpeedY += Speed;
}
else if (gravity == false)
{
SpeedY -= Speed+50;
}
SpeedX = SpeedX * FrictionX;
SpeedY = SpeedY * FrictionY;
Canvas.SetLeft(Meek, Canvas.GetLeft(Meek) + SpeedX);
Collide("x");
Canvas.SetTop(Meek, Canvas.GetTop(Meek) + SpeedY);
Collide("y");
double maxY = 0;
if (Canvas.GetBottom(Meek) > maxY)
{
maxY = Canvas.GetBottom(Meek);
}
score = maxY;
}
}
}
【问题讨论】:
-
你需要流畅的动画吗?可以考虑 px by ox 位置的碰撞,但这很麻烦。例如,与他给定的点相比,你的小人物的边缘在哪里。相反,我可能会根据更大的正方形网格来考虑游戏区域。然后它们可以由一个二维数组表示,并由整数 X、Y 索引。当两个对象的 X,y 坐标相同时,就会发生碰撞。像地板这样的物体可以填满一个正方形,所以你不能进入那个正方形。
标签: c# wpf game-development