【问题标题】:Unity3d: How to make a sprite point to mouse click?Unity3d:如何使精灵指向鼠标单击?
【发布时间】:2016-06-23 20:56:03
【问题描述】:

在 Unity3d 中,我试图让一个精灵“查看”我单击鼠标的位置。 This similar question 没有回答我的问题,因为它是针对 libgdx 的,并且是 Java 语言,而不是 C#。虽然这个other question 也很相似,但它涉及的是 XNA 而不是 Unity3d。 Unity 文档中关于 Euler 和 Quaternion 旋转的示例似乎集中在非交互式旋转。

我怀疑光线投射可能是可能的解决方案的一部分,但我的印象是(可能是错误的)它最适用于我没有使用的对撞机。我现在很困惑,需要更有经验的人来帮忙。

也可能是我不太了解(看起来像)在 3d 环境中使用 2d 精灵的 2d 点击。我只希望精灵以 2d 方式旋转。

再次,我想在单击鼠标右键时获取鼠标的位置,计算 GameObject 与鼠标单击之间的角度,然后将对象指向鼠标单击。

using UnityEngine;
using System.Collections;

public class LookAtClickPoint2d : MonoBehaviour {

    public Vector3 mousePosition;

    private Camera cam;

    // Use this for initialization
    void Start () 
    {
        cam = Camera.main;
    }

    // Update is called once per frame
    void Update() 
    {

        mousePosition = cam.ScreenToWorldPoint(Input.mousePosition);
        Vector3 targetDir = mousePosition - transform.position;

        if (Input.GetMouseButton (1)) 
        {
            //transform.Rotate(targetDir); /*<---This is @joeblow's suggestion.*/
            /*below is @mgear's suggestion*/
            Vector3 perpendicular = Vector3.Cross(transform.position-mousePosition, Vector3.forward);
            transform.rotation = Quaternion.LookRotation(Vector3.forward, perpendicular);
        }
    }
}

@mgear 的回答让我明白了这一点: 虽然在图片中并不明显,但精灵仅指向相机视图的中心,而不是鼠标位置。

@joeblow 的回答让我明白了这一点: 虽然精灵指向鼠标位置,但它们不会保持垂直。而且他们只移动一次!所以它没有回答我的问题。(我认为 Unity 试图以某种方式解释鼠标在 3d 空间中的位置,而不是 2d。)

【问题讨论】:

  • 假设x是精灵和鼠标点击之间的水平距离,y是垂直距离,你可以通过Arctan(y/x)获得旋转,然后你在@987654331上设置旋转@
  • 永远,永远,永远不要接触四元数或 .rotation。只需使用“旋转”使其旋转。如果您确实想简单地设置角度,只需 .eulerAngles =

标签: c# unity3d 2d sprite


【解决方案1】:

在此示例中,您希望将哪个轴朝向鼠标的选项很少: https://gist.github.com/unitycoder/5366a610599b503a40e9

【讨论】:

  • 非常接近我想要做的,唯一的就是它指向相机的中心,而不是鼠标位置。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-26
相关资源
最近更新 更多