c# - 用于使角色左右移动的 Unity UI 按钮不起作用

标签 c# unity3d

我正在为手机制作 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 按钮调用了这些函数,JumpAttack 工作得很好,但是 LeftRight 不行不工作。

这是我的按钮脚本的属性:

Button (Script)

最佳答案

希望它有用:

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/

相关文章:

c# - 为什么我的异常堆栈跟踪总是指向最后一个方法行?

c# - 我如何或可以使用 Windows Azure 移动服务查询 WindowsPhone8 应用程序中的多个表?

c# - unity C# 如何获取玩家的国家、城市或位置

c# - 在添加新力之前从 Rigidbody 移除先前的力

c# - 属性上的 SetValue 不更新对象

c# - SharpSSH 卡在 C# SSH 应用程序中的无限流读取中

c# - 秒表多任务ElapsedMilliseconds计算

c# - 安全通信 PHP (phpseclib) 和 C# (Unity 3D)

c# - 在 Unity 的 C# 中使用静态变量的最佳实践是什么

c# - 在 Unity 中使用捏合手势缩放 ScrollView 内容的正确方法是什么?