繁体   English   中英

如何根据鼠标位置旋转对象的位置?

[英]How to rotate the position of an object based on mouse position?

我现在正在使用此代码将坦克炮塔对象向鼠标位置旋转:

Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
Physics.Raycast(ray, out hit, range);
Vector3 dir = hit.point - transform.position;
Quaternion lookRotation = Quaternion.LookRotation(dir);
Vector3 rotation = lookRotation.eulerAngles;
transform.rotation = Quaternion.Euler(0f, rotation.y, 0f);

即使射线没有击中任何物体(将鼠标指向没有引发任何物体的位置)(击中为false),有没有办法产生旋转? 还有没有更好的方法来提供更好的解决方案?

谢谢。

基本上,我只是获得鼠标在屏幕上的位置,将其与目标对象进行比较,将其转换为度数,然后围绕所需的轴旋转对象(Y为topDown 3D空间,Z为2D)。

void RotateTowards()
    {
        var mouse = Input.mousePosition;
        var screenPoint = Camera.main.WorldToScreenPoint(tankTransform.localPosition);
        var offset = new Vector2(mouse.x - screenPoint.x, mouse.y - screenPoint.y);
        var angle = Mathf.Atan2(offset.y, offset.x) * Mathf.Rad2Deg;
        transform.rotation = Quaternion.Euler(0, angle, 0);
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM