简体   繁体   English

简单的方法来检测精灵是否被触摸?

[英]Easy way to detect if sprite was touched?

I have two sprites and they need to be touched at the same time so I made two Vector2 xy and xy1. 我有两个精灵,需要同时触摸它们,因此我制作了两个Vector2 xy和xy1。

//xy = x and y coordinate of pointer 1
//xy1 = x x and y coordinate of pointer 2

//faces is the class for the sprites

 if(xy.x >= faces.faceSpr.getX() && xy.x <= faces.faceSpr.getX() + faces.faceSpr.getWidth() &&               //detecting if xy and xy1 are inside the sprites
                    xy.y >= faces.faceSpr.getY() && xy.y <= faces.faceSpr.getY() + faces.faceSpr.getHeight() &&         //*
                    xy1.x >= faces.faceSpr1.getX() && xy1.x <= faces.faceSpr1.getX() + faces.faceSpr1.getWidth() &&     //*
                    xy1.y >= faces.faceSpr1.getY() && xy1.y <= faces.faceSpr1.getY() + faces.faceSpr1.getHeight())      //*
                score += 1;
            else if(xy1.x >= faces.faceSpr.getX() && xy1.x <= faces.faceSpr.getX() + faces.faceSpr.getWidth() &&        //*
                    xy1.y >= faces.faceSpr.getY() && xy1.y <= faces.faceSpr.getY() + faces.faceSpr.getHeight() &&       //*
                    xy.x >= faces.faceSpr1.getX() && xy.x <= faces.faceSpr1.getX() + faces.faceSpr1.getWidth() &&       //*
                    xy.y >= faces.faceSpr1.getY() && xy.y <= faces.faceSpr1.getY() + faces.faceSpr1.getHeight()) 

I haven't tested yet if this code works, is there an easier and better way of doing it? 我尚未测试此代码是否有效,是否有更简便更好的方法?

EDIT: 编辑:

I tried to use getBoundingRectangle() method and it works but I have problem on setting it's postion. 我尝试使用getBoundingRectangle()方法,它可以正常工作,但是在设置位置时出现问题。

sprite.getBoundingRectangle().setPosition(x,y);
// then I check if it works
System.out.println(sprite.getBoundingRectangle().getPostion);

but the result is always 0.0, 0.0 但结果始终是0.0,0.0

The solution is simple. 解决方案很简单。 Get the rectangle of it and make a contains call. 获取它的矩形并进行包含调用。

sprite.getBoundingRectangle().contains(new Vector2D(touch.x,touch.y)); //or
sprite.getBoundingRectangle().contains(touch.x, touch.y); //

Make sure that you unprojected correct. 确保您未投影正确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM