赞
踩
一 Button的点击
1.1 新建UI -> Button
1.2 在Button上面右击添加空物体
1.3 创建脚本挂载到空物体上面
脚本内容添加点击方法,来控制物体的显示隐藏
- using System.Collections;
- using System.Collections.Generic;
- using Unity.VisualScripting;
- using UnityEngine;
- using UnityEngine.EventSystems;
-
- public class NewMonoBehaviour : MonoBehaviour
- {
- public GameObject player;//获取物体
- private bool isActivity = true;
- private void Awake()
- {
- player = GameObject.Find("Player");
- }
-
- // Start is called before the first frame update
- void Start()
- {
- }
-
- void Update()
- {
- }
-
- // 按钮点击事件
- public void OnMyClick()
- {
- isActivity = !isActivity;
- //显示或者隐藏
- player.SetActive(isActivity);
- }
- }
1.4 按钮上On Click的位置关联空物体,并选择空物体的脚本方法OnMyClick()
1.5 运行后就可能控制物体显示隐藏了
二 方向键控制移动
2.1 添加四个方向按钮
2.2 添加一个脚本,同时挂载到四个按钮上面
2.3 编写脚本,通过按钮名字判断是点击的哪个按钮,从而判断往哪个方向移动
- using System.Collections;
- using System.Collections.Generic;
- using Unity.VisualScripting;
- using UnityEngine;
- using UnityEngine.EventSystems;
-
- public class Controll : MonoBehaviour,IPointerDownHandler, IPointerUpHandler
- {
- public Rigidbody2D rbody;//获取刚体
-
- private void Awake()
- {
-
- rbody = GameObject.Find("Player").GetComponent<Rigidbody2D>();
- }
-
- void Start()
- {
-
- }
-
- // Update is called once per frame
- void Update()
- {
- if (isMove) {
- move();
- }
- }
-
- public bool isMove = false;//是否移动
-
- public void OnPointerDown(PointerEventData eventData)
- {
- isMove = true;
- getButton(eventData);
-
- }
-
- public void OnPointerUp(PointerEventData eventData)
- {
- isMove = false;
- }
-
- //获取点击的哪个按钮,方向
- private void getButton(PointerEventData eventData) {
- GameObject gameObject = eventData.selectedObject;
- Debug.Log(gameObject.name);
- switch (gameObject.name) {
- case "ButtonUp":
- moveX = 0;
- moveY = 1;
- break;
- case "ButtonLeft":
- moveX = -1;
- moveY = 0;
- break;
- case "ButtonBottom":
- moveX = 0;
- moveY = -1;
- break;
- case "ButtonRight":
- moveX = 1;
- moveY = 0;
- break;
- default:
- moveX = 0;
- moveY = 0;
- break;
- }
- }
-
- /**
- * 移动
- **/
- public float speed = 10f;//移动速度
- private int moveX;//方向 -1左 1右
- private int moveY;//方向 -1上 1下
- public void move() {
-
- Vector2 position = rbody.position;
- position.x += moveX * speed * Time.deltaTime;
- position.y += moveY * speed * Time.deltaTime;
- //transform.position = position;
- rbody.MovePosition(position);
- }
- }
2.4 运行可以看到物体可以往上下左右方法移动
2.5 总结:
- 脚本实现抬起按下事件的接口MonoBehaviour,IPointerDownHandler, IPointerUpHandler。
- 通过GameObject.Find("Player").GetComponent<Rigidbody2D>(),获取物体
- 添加变量是否移动isMove,在Update方法里面判断是否拦截移动
- OnPointerDown 按下的时候通过eventData.selectedObject,获取点击的哪个按钮,来判断上下左右方向
- 添加方向判断判断,按钮按下的时候赋值,int moveX;//方向 -1左 1右 int moveY;//方向 -1上 1下
- OnPointerUp 按键抬起的时候,ivMove变为false,不再更新移动位置
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。