[英]How to detect if two sprites are being touched at the same time?
我尝试了这个:
if(spr.getBoundingRectangles.contain(x,y)){
//do this
}
但是如何检测第二个指针是否触摸了另一个精灵?
编辑:
for(int i = 0; i < Constants.MAX_POINTERS; i++){
if(Gdx.input.isTouched(i)){
xy.set(Gdx.input.getX(i), Gdx.input.getY(i), 0);
xy1.set(Gdx.input.getX(i), Gdx.input.getY(i), 0);
WorldRenderer.camera.unproject(xy);
WorldRenderer.camera.unproject(xy1);
if(Spr.getBoundingRectangle().contains(xy.x, xy.y) &&
Spr1.getBoundingRectangle().contains(xy.x, xy.y))
score += 1;
}
}
发生的是xy
和xy1
始终相同,当我用第二个指针触摸屏幕时,它们将都切换到新坐标,而不是xy和xy1都具有两个不同的x,y。
您可以遍历所有指针,检查它们是否触摸屏幕,然后检查位置是否与精灵位置重叠
final int MAX_POINTERS = 5;
...
for(int i = 0; i < MAX_POINTERS; i++)
{
if( Gdx.input.isTouched(i) )
{
int x = Gdx.input.getX(i);
int y = Gdx.input.getY(i);
if( sprite.getBoundingRectangle().contains(x, y) ) //instead of checking one sprite iterate over sprites array
{
System.out.println("The sprite is touched!");
}
//if... - or just add more ifs
}
}
您需要定义指针的最大数量以对其进行迭代-据我所知,Libgdx支持多达20个指针
关于编辑:
当然,它们是相同的... :)您将相同的价值赋予vetors 。 上面的示例更加通用,您需要-如果您知道有两个指针 ,则可以使用:
if( Gdx.input.isTouched(0) && Gdx.input.isTouched(1) ) //because if two pointers are touching screen there is a chance that they are touching two sprites
{
xy.set(Gdx.input.getX(0), Gdx.input.getY(0), 0);
xy1.set(Gdx.input.getX(1), Gdx.input.getY(1), 0);
//checking if pointer 1 is touching sprite 1 and pointer 2 is touching sprite 2 OR VICE VERSA
if( (Spr.getBoundingRectangle().contains(xy.x, xy.y) && Spr1.getBoundingRectangle().contains(xy1.x, xy1.y))
||
(Spr.getBoundingRectangle().contains(xy1.x, xy1.y) && Spr1.getBoundingRectangle().contains(xy.x, xy.y))
)
{
score += 1;
}
}
或只是创建一个函数,如果您要传递给它的所有子画面都被触摸(该函数实际上可以处理两个以上的子画面),它将返回true
boolean allTouched(Array<Sprite> sprites)
{
int spritesCount = sprites.size;
int spritesTouched = 0;
for(int i = 0; i < MAX_POINTERS; i++)
{
if( Gdx.input.isTouched(i) )
{
for(Sprite sprite : sprites)
{
if( sprite.getBoundingRectangle().contains(Gdx.input.getX(i), Gdx.input.getY(i)) )
{
spritesTouched++;
sprites.removeValue(sprite, true); //to not doubling the same sprite
}
}
}
}
return spritesCount == spritesTouched ;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.