Makes buttons in games !? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Makes buttons in games !?

It's my first try to build a game ☝ I searched alot on Google and I found alot of guys who told me how to build on PC with keyboards .... But no one tell me how to be build to be suitable for touchscreens . . . In brief Let's say I build a simple snake 🐍 game . I put functions for keys( up down left right) on keyboard on PC but I get mazed to make buttons for movement on my phone ! https://code.sololearn.com/W179WPJJcS3n/?ref=app

18th Jan 2019, 10:40 PM
2Math
2Math - avatar
9 Answers
+ 2
Move the following event functions to global scope, outside of main() function goLeft(){ v = -t; w = 0; } function goUp(){ v = 0; w = -t; } function goRight(){ v = t; w = 0; } function goDown(){ v = 0; w = t; } And the way you define functions inside switch case is wrong. https://code.sololearn.com/Wcoq9ZA0ew17/?ref=app
19th Jan 2019, 12:45 AM
Calviղ
Calviղ - avatar
+ 4
The HTML: <button onclick="goLeft();">Left</button> <button onclick="goRight();">Right</button> <button onclick="goDown();">Down</button> <button onclick="goUp();">Up</button> The JS: function goLeft() { // All your code in the switch statement for going left... } function goRight() { // All your code in the switch statement for going right... } function goDown() { // All your code in the switch statement for going down... } function goUp() { // All your code in the switch statement for going up... }
18th Jan 2019, 10:59 PM
Rowsej
Rowsej - avatar
+ 4
1. Without using window.onload You define a function for a button in this way: https://code.sololearn.com/W1jG7sDx95T6/?ref=app Note: the function must have the same name. 2. With using window.onload You use addEventListener, in this way: https://code.sololearn.com/WriFNOoR188j/?ref=app
19th Jan 2019, 12:51 PM
Gordon
Gordon - avatar
+ 2
Thanks Rowsej for helping ! . Yeah I tried that before and give me that onclick buttons in HTML aren't defined And I tried it again and the same error , of course there's something I miss but I don't know what it is
18th Jan 2019, 11:32 PM
2Math
2Math - avatar
+ 2
Thanks Calviղ it works perfect ,,
19th Jan 2019, 4:49 PM
2Math
2Math - avatar
+ 2
Thanks Gordon now I understand how it works !
19th Jan 2019, 4:50 PM
2Math
2Math - avatar
+ 1
The best ever in the world
19th Jan 2019, 2:57 AM
Todd Rick
0
I don't understand
19th Jan 2019, 2:56 AM
Todd Rick
0
no
19th Jan 2019, 2:57 AM
Todd Rick