c# - 按钮不调用 OnPointerDown() 方法
问题描述
所以我决定通过将桌面上的 Pacman 游戏教程修改为 Android 游戏来学习 Unity。现在,我尝试将精灵脚本上的输入键从箭头键替换为 UI 按钮。然后将按钮拖动到精灵输入字段。 这是我的精灵上的输入字段图像
当我按下按钮时应该执行波纹管代码。但是,该按钮似乎没有触发任何方法。
if (rightButton.IsInvoking("OnPointerDown")){
Debug.Log("OnPOinterDOwn() method is called");
这是我的精灵的完整代码:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class PacmanMove : MonoBehaviour {
public float speed = 0.4f;
Vector2 dest = Vector2.zero;
public Button rightButton;
public Button leftButton;
public Button upButton;
public Button downButton;
// Use this for initialization
void Start () {
dest = transform.position;
}
//Update is called in fixed time interval
void FixedUpdate() {
//Move closer to Desstination
Vector2 p = Vector2.MoveTowards(transform.position, dest, speed);
GetComponent<Rigidbody2D>().MovePosition(p);
//Check for input if not moving
if ((Vector2)transform.position == dest) {
if (Input.GetKey(KeyCode.UpArrow) && valid(Vector2.up))
dest = (Vector2)transform.position + Vector2.up;
if (Input.GetKey(KeyCode.RightArrow) && valid(Vector2.right))
dest = (Vector2)transform.position + Vector2.right;
if (Input.GetKey(KeyCode.DownArrow) && valid(-Vector2.up))
dest = (Vector2)transform.position - Vector2.up;
if (Input.GetKey(KeyCode.LeftArrow) && valid(-Vector2.right))
dest = (Vector2)transform.position - Vector2.right;
//Bellow code supposed to be trigger when my UI button is pressed
if (rightButton.IsInvoking("OnPointerDown")){
Debug.Log("OnPointerMethod() is called");
}
}
// Animation Parameters
Vector2 dir = dest - (Vector2)transform.position;
GetComponent<Animator>().SetFloat("DirX", dir.x);
GetComponent<Animator>().SetFloat("DirY", dir.y);
}
bool valid (Vector2 dir) {
//Cast line from 'next to Pac-Man' to 'Pac-man'
Vector2 pos = transform.position;
RaycastHit2D hit = Physics2D.Linecast(pos + dir, pos);
return (hit.collider == GetComponent<Collider2D>());
}
}
有人能告诉我我错过了什么吗?
解决方案
在做了更多教程之后,我已经解决了这个问题。结果我必须在我的按钮上调用事件触发器。我还编写了另一个附加到按钮的脚本,它将从事件触发器中调用,并在精灵上设置布尔输入。
我在我的中等帖子上详细说明。
推荐阅读
- android - 如何从火力基地获取位置并对汽车标记进行动画处理
- ruby-on-rails - 如何使用 Waitr::Browser 显示动态站点内容以供 Nokogiri 抓取
- go - 实现一个通用的参数方法
- matlab - MATLAB 信号处理工具箱的重采样功能不适用于“线性”方法
- django - 关闭了运行服务器的终端窗口,但在尝试重新运行服务器时说端口仍在使用中
- swift - swiftui 文本文件和按钮内的按钮
- python - 尝试在列表上使用排序方法但不起作用。我已经包含了适用于 sorted 方法的代码,但不明白为什么它不起作用
- javascript - file_get_contents 到 json 数组
- sql - Sql查询创建下表
- python - Google Colaboratory Python 安装错误:TA-Lib