Recently I have started messing around with the amazing Kivy. If you've not heard of it, it's a relatively easy way to write apps in python that will run on Android, iOS, OS X and Linux (without changing your code for each one). If you have heard of it already, it's also that. The best resources I've found for learning it so far have been Kivy's own Pong tutorial, and Alexander Taylor's excellent video guides.
From time to time I'll post things here that I pick up which I found useful, and the first of these is a little touch screen issue which I managed to resolve. I am trying to create a simple game, and I just want one input. Every time the player touches the screen it moves a balloon downwards, kind of like a jump in many other games. So I needed a touch screen input.
Kivy's Pong tutorial uses the built-in function "on_touch_move", so this seemed like a natural place for me to start, using this code in my main.py python file:
def on_touch_move(self, touch): self.avatar.jump()
Seems simple enough, right? This calls the function "self.avatar.jump", to make the avatar jump, whenever the screen is pressed. The problem I had (on both my laptop and my Android phone) is that its functionality is quite intermittent. Sometimes the screen would register my press, and sometimes it wouldn't. This is obviously not good enough for a game that relies on reactions, good timing and a single user input. The "on_touch_move" function also registers the position of any screen touch, and perhaps this is slowing things down. All I needed was the fact that the screen was touched.
To get around this issue you can use a button instead of the "on_touch_move" function. Whenever this button is pressed, a specific function is called. You can also make this button fill the screen, and make it transparent, so that we have the functionality I wanted. To use this there is actually no extra code in the main.py python file, and instead it is held in the .kv file:
Button: height: self.parent.height width: self.parent.width background_color: (0, 0, 0, 0) on_press: root.avatar.jump()
The first line obviously just tells kivy we are making a button. The next two set the height and width of the button: here we have made it inherit its parent's size, so as to make it fill the screen. The last element of the background_color setting (the last 0 in (0, 0, 0, 0)) is the alpha, i.e. transparency. 1 would have been totally opaque, and is the default, so we must set this to 0 to be transparent. The final line tells the button what function to trigger. This has to be a function held within the main.py file, obviously.
That's it! I was really worried I would have to give up on kivy altogether when I found this intermittent and unreliable touch screen problem, which would have been a real shame as it has huge potential. However, my faith has been restored.
No comments:
Post a Comment