简体   繁体   English

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

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

I'm using this code at the moment to rotate a tank turret object towards the 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);

Is there any way to create a rotation even when the ray doesn't hit any object, (pointing the mouse where there is no object initiated) (hit is false)? 即使射线没有击中任何物体(将鼠标指向没有引发任何物体的位置)(击中为false),有没有办法产生旋转? Also is there a better approach for a better solution? 还有没有更好的方法来提供更好的解决方案?

Thanks. 谢谢。

Basically, I just get the position of the mouse on screen, compare it to the target object, convert that to degrees, and rotate the object around the wanted axis (Y for topDown 3D space, Z for 2D). 基本上,我只是获得鼠标在屏幕上的位置,将其与目标对象进行比较,将其转换为度数,然后围绕所需的轴旋转对象(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