所以我正和朋友一起开发游戏引擎,目前我正在进行碰撞检测:
以下是移动和寻找检测的代码
private void Timer_Tick(object sender, EventArgs e)
{
string[] text = GameCode.Text.Split(new string[] { System.Environment.NewLine }, StringSplitOptions.None);
foreach (KeyValuePair<string, Panel> kvp in objects)
{
if (running)
{
if (text.Contains("Move " + kvp.Key + " Left"))
{
Point loc = kvp.Value.Location;
loc.X = loc.X - 1;
kvp.Value.Location = loc;
}
if (text.Contains("Move " + kvp.Key + " Right"))
{
Point loc = kvp.Value.Location;
loc.X = loc.X + 1;
kvp.Value.Location = loc;
}
if (text.Contains("Move " + kvp.Key + " Up"))
{
Point loc = kvp.Value.Location;
loc.Y = loc.Y - 1;
kvp.Value.Location = loc;
}
if (text.Contains("Move " + kvp.Key + " Down"))
{
Point loc = kvp.Value.Location;
loc.Y = loc.Y + 1;
kvp.Value.Location = loc;
}
if (text.Contains("Collide " + kvp.Key + " + " + kvp.Key))
{
MessageBox.Show("Name1: " + kvp.Key + " + Name2: " + kvp.Key);
}
}
}
//Invalidate();
DoubleBuffered = false;
}
这是用于查找两个不同对象的代码,然后我将添加碰撞检测。
if (text.Contains("Collide " + kvp.Key + " + " + kvp.Key))
{
MessageBox.Show("Name1: " + kvp.Key + " + Name2: " + kvp.Key);
}
但是当我输入时,碰撞obj1 + obj2 直到我将obj2更改为obj1然后它会弹出obj1 + obj1,但我想输入碰撞obj1 + obj2,然后一些如何检测它们之间的碰撞,但我不知道如何实现这个,我已经多次尝试了。
碰撞的逻辑是:
if (text.Contains("Collide " + kvp.Key + " + " + kvp.Key))
{
if (kvp.Value.Bounds.IntersectWith(kvp.Value.Bounds))
{
//DO something
}
}
答案 0 :(得分:0)
正如评论中所提到的,循环代码内部正在寻找单个密钥,这就是为什么在键入Collide obj1 + obj2
我建议将此逻辑移到foreach
循环之外,并在每次移动时跟踪对象键。
private void Timer_Tick(object sender, EventArgs e)
{
string[] text = GameCode.Text.Split(new string[] { System.Environment.NewLine }, StringSplitOptions.None);
List<KeyValuePair<string, Panel>> movedObjects = new List<KeyValuePair<string, Panel>>();
foreach (KeyValuePair<string, Panel> kvp in objects)
{
if (running)
{
if (text.Contains("Move " + kvp.Key + " Left"))
{
Point loc = kvp.Value.Location;
loc.X = loc.X - 1;
kvp.Value.Location = loc;
movedObjects(kvp);
}
if (text.Contains("Move " + kvp.Key + " Right"))
{
Point loc = kvp.Value.Location;
loc.X = loc.X + 1;
kvp.Value.Location = loc;
movedObjects(kvp);
}
if (text.Contains("Move " + kvp.Key + " Up"))
{
Point loc = kvp.Value.Location;
loc.Y = loc.Y - 1;
kvp.Value.Location = loc;
movedObjects(kvp.Key);
}
if (text.Contains("Move " + kvp.Key + " Down"))
{
Point loc = kvp.Value.Location;
loc.Y = loc.Y + 1;
kvp.Value.Location = loc;
movedObjects(kvp);
}
}
if(movedObjects.Count() > 1) // change this logic accordingly when there more than two objects can move.
{
MessageBox.Show("Name1: " + movedObjects[0].Key + " + Name2: " + movedObjects[1].Key);
if (movedObjects[0].Value.Bounds.IntersectWith(movedObjects[1].Value.Bounds))
{
//DO something
}
}
}
//Invalidate();
DoubleBuffered = false;
}