首先,我是一名学生,所以我恳请你耐心回答。顺便说一下,我也不会说英语。一切都开始了,因为我要参加一个游戏即兴演奏会,我已经开始写(或试着写)一个简单的“物理”代码,我真的认为他会很容易。我正在处理类,并使用hitTestObject进行冲突检测。实际上,我从一开始就有问题,但我一直在努力解决它。在这个时候,代码真的很糟糕,我已经在考虑用另一种方式来做这件事。但有件事让我感到困惑。这是我已经写好的代码的一部分(可能看起来很新手)。大部分代码都是废话,看看最后的"else if“就知道了。注意:这是"block“类,"obj”是播放器的电影剪辑。
public function checkObj(obj:MovieClip):void
{
if (this.hitTestObject (obj))
{
if (this.y < obj.y)
{
if (this.x - this.width/2 <= obj.x+obj.width/2 && this.x + this.width/2 >= obj.x-obj.width/2)
{
downCol = true;
}
}
else if (this.y + this.height/2 > obj.y-obj.height/2)
{
if (this.x - this.width/2+2 <= obj.x+obj.width/2 && this.x + this.width/2-2 >= obj.x-obj.width/2)
{
upCol = true;
onBox = true;
}
}
if (this.x - this.width/2 >= obj.x+obj.width/2-2)
{
if (this.y - this.height/2<= obj.y+obj.height/2&& this.y + this.height/2>= obj.y-obj.height/2)
{
leftCol = true;
}
}
else if (this.x + this.width/2 <= obj.x-obj.width/2-2)
{
if (this.y + 5>= obj.y-obj.height/2 && this.y - 5<= obj.y+obj.height/2)
{
trace ("Collided on right");
rightCol = true;
}
}
}
}
由于某些原因,这种方式不起作用。它永远不会给我返回消息。
但如果我做一点改变:
public function checkObj(obj:MovieClip):void
{
if (this.x + this.width/2 <= obj.x-obj.width/2-2)
{
objOnRight = true;
}
if (this.hitTestObject (obj))
{
//...
else if (objOnRight == true)
{
if (this.y + 5>= obj.y-obj.height/2 && this.y - 5<= obj.y+obj.height/2)
{
rightCol = true;
trace ("Collided on right");
}
}
}
}
它起作用了。只是因为我在测试碰撞之前检查了"obj“的X轴。我知道这段代码很糟糕,但是如果有人能帮助我理解这个错误,也许可以指导我找到一个更有效的解决方案,我会非常感激的!谢谢。
发布于 2015-10-12 22:10:36
在最后一次尝试此方法,如果
else if (this.x + this.width / 2 <= obj.x + obj.width / 2 - 2) {
if (this.y + 5 >= obj.y - obj.height / 2 && this.y - 5 <= obj.y + obj.height / 2) {
trace("Collided on right");
rightCol = true;
}
}
只需将"-“改为"+”即可。
发布于 2015-10-13 20:10:14
好吧,算了吧。我写了一段全新的代码,没有使用hitTest,它运行起来非常棒。我认为Math.abs用负数解决了这个问题。谢谢你的帮助,kare81。代码如下:
public function checkObj(obj:MovieClip,place:int):void
{
if (obj.x + obj.width / 2 > this.x - width / 2 && obj.x < this.x - width / 2 + 7 && Math.abs (obj.y - y) < height / 2)
{
obj.x = this.x - width / 2 - obj.width / 2;
}
if (obj.x - obj.width / 2 < this.x +width / 2 && obj.x > this.x + width / 2 - 7 && Math.abs (obj.y - y) < height / 2)
{
obj.x = this.x +width / 2 + obj.width / 2;
}
if (Math.abs (obj.x- this.x) < width / 2 + obj.width / 2 && obj.y<y-height/2 && obj.onFloor > y-height/2 && obj.onBlock != place)
{
obj.onFloor = y - height / 2;
obj.onBlock = place;
}
if (Math.abs (obj.x - this.x) >= width / 2 + obj.width / 2 && obj.onBlock == place)
{
obj.onFloor = 450;
}
if (obj.y - obj.height / 2 < y + height /2 && obj.y > y && Math.abs (obj.x - this.x) < width / 2 + obj.width / 2)
{
obj.y = y + height / 2 + obj.height / 2;
}
}
https://stackoverflow.com/questions/33072987
复制相似问题