- Home /
Adding Touch Controls to Car Game
hello. Ive spent a couple hours looking on the forums and i am just really confused and dont know how to properly handle this. I have made 2 buttons. A gas pedal (gas) and a brake pedal (brake). I have added them to my gui. I am having trouble adding these buttons to the code and making it so when the gas is pressed or held, the car goes. and when the brake is pressed or held, it starts stopping.
Here is the car game movement code
Any help would be appreciated.
OnGUI{
if(GUI.Button(Rect()),Gas) {
// gas function
}
if(GUI.Button(Rect()),Brake) {
// break function
}
}
I didn't look at your code but generally if you are using a GUI button it's something like that
I don't do mobile but I'm assu$$anonymous$$g the if(GUI.Button...) struct works the same - test it and see or search. Are you using OnGUI or are you using something like if(Input.GetAxis($$anonymous$$eyCode.*))?
Forgot to say I am using a c# script and will need mul$$anonymous$$ch on my game. I Did some research and don't think this works with mul$$anonymous$$ch. How would you do the if(Input.GetAxis($$anonymous$$eyCode)) code? I'm having trouble implementing that into my code. Thanks for all your help!!
What is the best way to approach this? I am still very confused despite all the research.
Answer by POLYGAMe · Feb 18, 2014 at 08:55 PM
Here's how I did it in my game Get Gravel (these are GUITexture buttons):
for (var touch : Touch in Input.touches)
{
if (GasButton.HitTest(touch.position))
{
bBrakeButtonPressed = false;
bGasButtonPressed = true;
}
else if (BrakeButton.HitTest(touch.position))
{
bGasButtonPressed = false;
bBrakeButtonPressed = true;
}
if (LeftButton.HitTest(touch.position))
{
bRightButtonPressed = false;
bLeftButtonPressed = true;
}
else if (RightButton.HitTest(touch.position))
{
bLeftButtonPressed = false;
bRightButtonPressed = true;
}
}
Then just use those bools to control your car.
Ignore the dodgy formatting... I think it's cos I cut the code from TextEdit.
Hi thanks for answering. Does this support mul$$anonymous$$ch? for example can I hold the gas down and the left button at the same time? And is this c#? Thank you!!!
Yup, supports multi touch. It counts through and detects each touch. This is in JS but the code should be pretty much identical, other than the for loop, which from looking at the docs would be:
foreach (Touch touch in Input.touches)
Don't forget to accept the answer as correct if this helps :)
When it says bBrakeButtonPressed do I just replace it with brakepressed because my button is named brake?
Those are just booleans I set up for my game. You can do whatever you want in there when the button is pressed. Also, you'll have to swap out the names of the buttons for the names of your GUITexture buttons.