How do I switch from * Input.GetAxis () * to UI buttons?
Hello! How do I switch from Input.GetAxis () to UI buttons in my code? The code below rotates an object on the Z axis depending on how long you hold down the arrows on the keyboard. It works perfectly on the keyboard but I want to put it on UI buttons. I tried a few ways but they didn't work . Can you help me please?
public float Rotation_Speed;
public float Rotation_Friction;
public float Rotation_Smoothness;
private float Resulting_Value_from_Input;
private Quaternion Quaternion_Rotate_From;
private Quaternion Quaternion_Rotate_To;
public void RotateUp()
{
Resulting_Value_from_Input += Input.GetAxis("Horizontal") * Rotation_Speed * Rotation_Friction;
Quaternion_Rotate_From = transform.rotation;
Quaternion_Rotate_To = Quaternion.Euler(0, 0, Resulting_Value_from_Input);
transform.rotation = Quaternion.Lerp(Quaternion_Rotate_From, Quaternion_Rotate_To, Time.deltaTime * Rotation_Smoothness);
}
public void RotateDown()
{
Resulting_Value_from_Input += Input.GetAxis("Horizontal") * Rotation_Speed * Rotation_Friction;
Quaternion_Rotate_From = transform.rotation;
Quaternion_Rotate_To = Quaternion.Euler(0, 0, Resulting_Value_from_Input);
transform.rotation = Quaternion.Lerp(Quaternion_Rotate_From, Quaternion_Rotate_To, Time.deltaTime * Rotation_Smoothness);
}
Thing is if you want to move through button press, you can't calculate speed using time, since the button press acts instantaneously. You need to create a button, and when you click it, you call RotateUp() or RotateDown(). It would be better if you add an argument to theese functions, like RotateUp(float Speed), so you can call that function from the button with a set speed.
Sure. You'll need to create the buttons you want for movement, and get their references in script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI
public class MoveButton : MonoBehaviour
{
[SerializeField]
Button _RotateLeftButton;
[SerializeField]
Button _RotateRightButton;
[SerializeField]
GameObject character;
private void Start()
{
_RotateLeftButton.onClick.AddListener(delegate { RotateRight(); });
_RotateRightButton.onClick.AddListener(delegate { RotateLeft(); });
}
}
You should get a reference to watever script you are using to move your character, and then use the RotateUp() or RotateDown() from that script on those lines of code with AddListener(). Also, you should be abre to drag the buttons you want to use in the inspector, on the GameObject holding the code I gave you.
Your answer
Follow this Question
Related Questions
OnTriggerEnter2D not working 2 Answers
LookAt in 2d is not working Again :/ 0 Answers
Trigger events with bullets 0 Answers