GameObject transform.Rotate()

ぐ巨炮叔叔 提交于 2019-12-11 14:45:31

问题


I have a question. I have 4 objects on the screen and a projectile as in the picture below. image source

When I click on an object in the 4 projectile it changes position indicating to the object I clicked on. This is the code used but it does not work.

public GameObject Tun;
public GameObject[] robotColliders;
public GameObject[] Robots;

 foreach(GameObject coll in robotColliders)
    {
        coll.GetOrAddComponent<MouseEventSystem>().MouseEvent += SetGeometricFigure;
    }

   private void SetGeometricFigure(GameObject target, MouseEventType type)
{
    if(type == MouseEventType.CLICK)
    {
        Debug.Log("Clicked");
        int targetIndex = System.Array.IndexOf(robotColliders, target);
        Tun.transform.DORotate(Robots[targetIndex].transform.position, 2f, RotateMode.FastBeyond360).SetEase(Ease.Linear);
    }
}

I was thinking about using the component DORotate(), But it does not work anyway. Does anyone know how to fix this problem?


回答1:


One method would be to use a quaternion to set the rotation about the z-axis, using a vector between the object and your arrow to get the angle.

Vector2 dir = Robots[targetIndex].transform.position - Tun.transform.position;
Tun.transform.rotation = Quaternion.Euler(0, 0, Mathf.atan2(dir.y, dir.x)*Mathf.Rad2Deg - 90); // may not need to offset by 90 degrees here;



回答2:


That's a lot of moving parts for such a simple task. Unity manual has an example that is the correct (most efficient) way to do this kind of things (see https://docs.unity3d.com/ScriptReference/Mathf.Atan2.html):

using UnityEngine;
using System.Collections;

public class ExampleClass : MonoBehaviour {
    public Transform target;
    void Update() {
        Vector3 relative = transform.InverseTransformPoint(target.position);
        float angle = Mathf.Atan2(relative.x, relative.z) * Mathf.Rad2Deg;
        transform.Rotate(0, angle, 0);
    }
}

This operate by rotating an object around Y axis (that's why Atan2 accounts for X and Z): if you need different axis just adapt the code by changing those.



来源:https://stackoverflow.com/questions/45841591/gameobject-transform-rotate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!