- Home /
Moving Player Left/Right with Buttons
I am creating a 2D Space Invaders game and I want to be able to move the player's ship side to side using "Left"/"Right" buttons (UI) i.e. run 'this' method as long as 'this' button is pressed.
I have also tried adding my buttons to input manager but I don't think it worked.
I have already created and placed the buttons but the script I attached to them does not work at all, including the debug print statement:
private PlayerController playerController;
void Start(){
playerController = GameObject.Find("Player").GetComponent<PlayerController>();
}
void Update () {
if (Input.GetButtonDown ("Right")) {
print ("RIGHT CLICKED");
playerController.transform.position += Vector3.right * 15.0f * Time.deltaTime;
}
}
Any and all help is appreciated :)
Answer by unit_nick · Sep 11, 2017 at 01:04 AM
I think you need GetButton()
Returns true while the virtual button identified by buttonName is held down.
https://docs.unity3d.com/ScriptReference/Input.GetButton.html
GetButtonDown()
You need to call this function from the Update function, since the state gets reset each frame. It will not return true until the user has released the key and pressed it again.
https://docs.unity3d.com/ScriptReference/Input.GetButtonDown.html
so change line 12 to
if (Input.GetButton ("Right")) {
Answer by Cuttlas-U · Sep 10, 2017 at 11:31 PM
hi; by buttons u mean buttons in the game ? or keys in the keyboard?
if number 1 is your problem then u cant do it like that u need to make it as a seperate function and call it when the button is pressed ( not put it in update);
send a screen shot so i can help u better;
Yes, #1 is my problem.
Did you mean I should create a separate function like this:
void movePlayer()
{
playerController.transform.position += Vector3.right * 15.0f * Time.deltaTime;
}
So should I run this function on my button's "On Click()" property?
yeah this is correct; but make it public so u can access it in button;
Ok so I did that:
public void movePlayer(){
playerController.transform.position += Vector3.right * 15.0f * Time.deltaTime;
}
Then I added it to my "Left" button's OnClick() however it doesn't work when I hold the button pressed, only when I keep clicking it - how do I make it so "movePlayer" keeps running while button is pressed?
Sorry for asking so much, I am a noob :)
Your answer
Follow this Question
Related Questions
How to Detect if a Button is Not Being Pressed 0 Answers
How do I highlight multiple buttons at once? 1 Answer
Button Action Triggering Multiple Times Per Click? 1 Answer
How to make UI buttons so my player can move along certain lines 0 Answers
I need to move a sprite when an UI button is clicked 1 Answer