首页 > 解决方案 > 通过鼠标单击统一控制对象旋转

问题描述

我需要统一的项目帮助

我想通过单击来停止每个对象。

到目前为止我所做的:
我所有的对象都会旋转,但是当我单击它们都停止的任何地方时,只有当我单击每个对象时,我才需要它们停止。

这是我的代码:

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);
        }
    }
}

标签: unity3d

解决方案


有两种好方法可以实现这一目标。这两种方式都要求您将一个对撞机附加到您的对象上。

一种是从相机通过光标将光线投射到场景中,以检查当前在光标下的对象。

第二种方法是使用统一的 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);
    }
}

推荐阅读