设计公司网站的主页怎么做,2021营业执照年检网上申报,互联网项目计划书,东莞企石网站设计一 Button的点击
1.1 新建UI - Button 1.2 在Button上面右击添加空物体 1.3 创建脚本挂载到空物体上面 脚本内容添加点击方法#xff0c;来控制物体的显示隐藏
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using Unit…一 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 updatevoid 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).GetComponentRigidbody2D();}void Start(){}// Update is called once per framevoid 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).GetComponentRigidbody2D()获取物体添加变量是否移动isMove在Update方法里面判断是否拦截移动OnPointerDown 按下的时候通过eventData.selectedObject获取点击的哪个按钮来判断上下左右方向添加方向判断判断按钮按下的时候赋值int moveX;//方向 -1左 1右 int moveY;//方向 -1上 1下OnPointerUp 按键抬起的时候ivMove变为false不再更新移动位置