Touching
Most games need to know when two things meet: the player and a coin, a bullet and an enemy, a ball and the edge.
Touching another sprite
Ask with the class of the other sprite. Use the arrow keys to collect the gems:
isTouchingSprite(Gem.class)asks: does it touch any gem?-
getTouchingSprite(Gem.class)gives you the gem it touches, ornull. Then you can move it, hide it orremove()it. isTouchingSprite(otherSprite)asks about one particular sprite.getTouchingSprites(Gem.class)gives all of them, as a list.
run() asks 60 times a second. While the player touches a gem, the
question is true in every frame. Make sure the touch ends: move the gem away,
hide it or remove it. Otherwise one touch counts many times.
Edges and colours
| Scratch | Java |
|---|---|
| <touching [edge v]?> | isTouchingEdge() |
| if on edge, bounce | ifOnEdgeBounce() |
| <touching color [#ff0000]?> | isTouchingColor(new Color(255, 0, 0)) |
| <color [#ff0000] is touching [#0000ff]?> | isColorTouchingColor(a, b) |
| (distance to [Sprite1 v]) | distanceToSprite(other) |
Hitboxes
A sprite touches with its hitbox: by default the rectangle around the visible pixels of its costume. Hidden sprites touch nothing.
Turn on debug mode to see the hitboxes. Press F12, or call
Window.getInstance().setDebug(true). Try it here:
When the rectangle is too large, give the sprite a smaller hitbox with
setHitbox. It is measured in the costume's pixels, from its top left corner:
this.setHitbox(new Rectangle(10, 20, 60, 40)); // x, y, width, height
Circle, Ellipse, Triangle and Polygon work too.
Next
- Sensing example: the mouse and own hitboxes
- isTouchingSprite in the reference