Detecting Object Touch
Monkey Forums/Monkey Beginners/Detecting Object Touch
| ||
What is the simplest method of detecting when a user either clicks or touches an object? Jason |
| ||
Vector distance? A vector class: http://www.monkeycoder.co.nz/Community/posts.php?topic=568&post=4319 Is point in rectangle? Function PointInRect:Bool(x:Float, y:Float, rx1:Float, ry1:Float, rx2:Float, ry2:Float) If x >= rx1 And x <= rx2 And y >= ry1 And y <= ry2 Then Return True End Function |
| ||
Depends what you mean by "object". Touch/click interaction is about collision detection on the screen projection of the "object". That can be anything from a simple point in rectangle check through to a camera vector raycast depending on what you're working with. |
| ||
Also, TouchX, TouchY and TouchHit will automatically give the appropriate mouse equivalents if there is no touch-screen, so a basic starting point in OnUpdate() could be: If TouchHit() > 0 If buttonRect.Contains( TouchX(), TouchY() ) DoButtonThing() Else ' Try more buttons etc. End End |
| ||
Basically I am using an image for a button and I want to know when the user touches or clicks on the button. Currently I am experimenting with TouchHit(), TouchX() and TouchY(). Jason |
| ||
Here is a simple button class. It's very basic but should give you something to play with, add images instead of rects etc. Import mojo Function Main:Int() New MyApp End Function Class MyApp Extends App Field button:ImageButton Method OnCreate:Int() ' create the new button Self.button = New ImageButton(200, 200, 100, 100) SetUpdateRate(60) Return True End Method Method OnUpdate:Int() Self.button.Update() Return True End Method Method OnRender:Int() Cls Self.button.Draw() Return True End Method End Class Class ImageButton Field x:Int, y:Int Field width:Int, height:Int Field pressed:Bool ' x/y : position of the button Method New(x:Int, y:Int, width:Int, height:Int) Self.x = x Self.y = y Self.width = width Self.height = height Self.pressed = False End Method Method Update() ' if screen is being touched If TouchDown(0) ' if the touch is overlaps with the button If RectsOverlap(TouchX(), TouchY(), 2, 2, Self.x, Self.y, Self.width, Self.height) ' set pressed to true Self.pressed = True Else ' set pressed to false Self.pressed = False EndIf Else Self.pressed = False EndIf End Method Method Draw() ' if the button is pressed If Self.pressed = True SetColor 200, 50, 50 DrawRect Self.x, Self.y, Self.width, Self.height Else SetColor 255, 255, 255 DrawRect Self.x, Self.y, Self.width, Self.height EndIf End Method End Class Function RectsOverlap:Int(x0:Float, y0:Float, w0:Float, h0:Float, x2:Float, y2:Float, w2:Float, h2:Float) If x0 > (x2 + w2) Or (x0 + w0) < x2 Then Return False If y0 > (y2 + h2) Or (y0 + h0) < y2 Then Return False Return True End |
| ||
I created a very good solution using knowledge I learned from the example posted by rIKmAN. Thanks to everyone for your input and help. Jason |