unity3d - 通过鼠标单击统一控制对象旋转
问题描述
我需要统一的项目帮助
我想通过单击来停止每个对象。
到目前为止我所做的:
我所有的对象都会旋转,但是当我单击它们都停止的任何地方时,只有当我单击每个对象时,我才需要它们停止。
这是我的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EarthScript : MonoBehaviour
{
public bool rotateObject = true;
public GameObject MyCenter;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
if(rotateObject == true)
{
rotateObject = false;
}
else
{
rotateObject = true;
}
}
if(rotateObject == true)
{
Vector3 axisofRotation = new Vector3(0,1,0);
transform.RotateAround(MyCenter.transform.position,axisofRotation, 30*Time.deltaTime);
transform.Rotate(0,Time.deltaTime*30,0,Space.Self);
}
}
}
解决方案
有两种好方法可以实现这一目标。这两种方式都要求您将一个对撞机附加到您的对象上。
一种是从相机通过光标将光线投射到场景中,以检查当前在光标下的对象。
第二种方法是使用统一的 EventSystem。您需要在相机上附加一个 PhysicsRaycaster,然后您会从事件系统中获得回调,从而简化检测(它由 Unity 处理,因此需要编写的代码更少)
using UnityEngine;
using UnityEngine.EventSystems;
public class myClass: MonoBehaviour, IPointerClickHandler
{
public GameObject MyCenter;
public void OnPointerClick (PointerEventData e)
{
rotateObject=!rotateObject;
}
void Update()
{
if(rotateObject == true)
{
Vector3 axisofRotation = new Vector3(0,1,0);
transform.RotateAround(MyCenter.transform.position,axisofRotation, 30*Time.deltaTime);
transform.Rotate(0,Time.deltaTime*30,0,Space.Self);
}
}
推荐阅读
- delta-lake - Delta Lake Table 元数据
- vue.js - Vue中从子组件导航到父组件
- selenium - 无法在 aws 设备场中截取屏幕截图以进行 android 应用程序自动化测试
- python - 如果对对象的引用递增/递减,则覆盖哪个函数
- java - 是否可以从 dex 文件中获取特定行的 java 代码?
- powershell - 如何使用 powershell 脚本传递 AWS SSM 输出
- sql - 在数据网格视图中显示查询结果
- java - 在 Spring 5 中传递对象的绑定列表时出现问题
- list - 如何计算存储在列表中的坐标的距离
- android - 具有永无止境的滚动动画的 Android 水平 RecycleView