简体   繁体   中英

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.

//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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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