我正在为手机制作 2D 游戏,我想使用 UI 按钮作为 Controller ,而不是我用来在笔记本电脑上测试游戏的键盘键。
这是我用于角色的代码:
public float moveSpeed;
private float moveVelocity;
public float jumpHeight;
public Transform tagGround;
public float groundCheckRadius;
public LayerMask playerMask;
private bool IsGrounded;
public Animator anim;
void Start ()
{
anim = GetComponent<Animator>();
}
void FixedUpdate ()
{
IsGrounded = Physics2D.OverlapCircle (tagGround.position, groundCheckRadius, playerMask);
}
void Update()
{
moveVelocity = 0f;
if (Input.GetKeyDown (KeyCode.W) && IsGrounded) {
Jump ();
}
if (Input.GetKey (KeyCode.D)) {
Right ();
}
if (Input.GetKey (KeyCode.A)) {
Left ();
}
GetComponent<Rigidbody2D> ().velocity = new Vector2 (moveVelocity, GetComponent<Rigidbody2D> ().velocity.y);
anim.SetFloat ("Speed", Mathf.Abs(GetComponent<Rigidbody2D> ().velocity.x));
anim.SetBool ("isGrounded", IsGrounded);
anim.SetBool ("Attacking", false);
if (Input.GetKeyDown (KeyCode.S)) {
Atk ();
}
if (GetComponent<Rigidbody2D> ().velocity.x > 0)
transform.localScale = new Vector3(1f, 1f, 1f);
else if (GetComponent<Rigidbody2D> ().velocity.x < 0)
transform.localScale = new Vector3(-1f, 1f, 1f);
}
我为每次按键设置了适当的功能,它们都运行良好。我用 UI 按钮调用了这些函数,Jump
和 Attack
工作得很好,但是 Left
和 Right
不行不工作。
这是我的按钮脚本的属性:
最佳答案
希望它有用:
public void OnPointerDown (PointerEventData eventData)
{
btn_pressed = true;
}
public void OnPointerUp (PointerEventData eventData)
{
btn_pressed = false;
}
if(btn_pressed)
{
//code
{
关于c# - 用于使角色左右移动的 Unity UI 按钮不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33734391/