- Home /
Use UI buttons for movement
So I have a basic 2d movement script that works with Input.GetAxis just fine. Now I'm trying to change the input to an on-screen d-pad for mobile. The problem is it is only running the movement once and then won't run the function again.
public void goRight(BaseEventData eventData) {
inputX = 1;
buttonheld = true;
Debug.Log ("You should be going right");
}
public void release(BaseEventData eventData){
buttonheld = false;
inputX = 0;
inputY = 0;
}
void Update ( )
{
if (buttonheld) {
if (inputX != 0 || inputY != 0) {
Move (inputX, inputY);
}
}
This is the gist of what I'm doing. Any insights would be great.
Answer by Mmmpies · Feb 24, 2015 at 09:16 AM
OK, not got access to Unity so this is just from my head. Place your four buttons/Images on screen and create a script that has eight public functions in it.
public void UpButtonOn()
{
upButton = true;
}
public void UpButtonOff()
{
upButton = false;
}
// repeat for left, right and down
Then in update just check those bool values and if true do the movement for that direction and handle events like left and right being pressed at the same time cancelling each other out. Call it DpadScript.cs
Drag that script onto the canvas directly.
On each button/image add an EventTrigger Component and add events to trigger on PointerEnter and PointerExit so for the up button add PointerEnter Event and drag the canvas (with the DpadScript on it) onto the slot that appears then from the dropdown select DpadScript -> UpButtonOn.
Add a PointerExit event and repeat but put it to DpadScript -> UpButtonOff.
Repeat that for each button adding a PointerEnter and PointerExit to the correct function to set the bool.
Should work but can't test as I don't have access to Unity at the moment.
Well that's essentially what I have but for whatever reason, it will run the move function once each then won't run again. So the buttons themselves work fine, but its a matter of connecting that event with the movement.
Your answer
Follow this Question
Related Questions
Have 2D Sprite Follow the Mouse in Straight Line 2 Answers
Unity 2D 4.6b UI: Why are instantiated prefab sprites rendering over UI elements? 1 Answer
How to Convert each 2D Array to GameObject 2 Answers
Moving object disappears then comes back 1 Answer
Top down 2d character controller sometimes walking backwards 1 Answer