简体   繁体   English

需要在 z 轴上旋转对象以指向/查看 xy 平面上的鼠标

[英]Need to rotate object on z axis to point at/look at mouse on xy plane

I am making a 3d side scroller.我正在制作一个 3d 横向卷轴。 need to rotate gun on z axis to face mouse on x,y plane.需要在 z 轴上旋转枪以在 x,y 平面上面对鼠标。 This is What I have so far.这是我到目前为止所拥有的。 Tried lookat and angle.尝试了外观和角度。 They sort of worked but would not point correctly.他们有点工作,但不会正确指出。 only half of the screen.只有一半的屏幕。 I just think I am missing something.我只是觉得我错过了一些东西。

void FixedUpdate()
{
    screenPosition = Input.mousePosition;
    screenPosition.z = 1; //mainCamera.nearClipPlane + 1;
    worldPosition = mainCamera.ScreenToWorldPoint(screenPosition);
    worldPosition.z = 0;

     
     
     //Angle?????

     

     transform.rotation = Quaternion.Slerp(rb.transform.rotation, 
     Quaternion.Euler(0,0,angle), 0.7f);
}

In order to get the angle there is no need to convert to world space.为了获得角度,无需转换为世界空间。

Indeed actually it is way easier to go the other way round and convert your objects position into screen space.事实上,实际上它更容易反过来并将您的对象位置转换为屏幕空间。

Then you can simply use theMathf.Atan2 on the pixel space delta然后你可以简单地在像素空间增量上使用Mathf.Atan2

var mousePosition = Input.mousePosition;
var objectScreenPosition = mainCamera.WorldToScreenPoint(rb.position);
var direction = mousePosition - objectScreenPosition; // No need to normalize btw
var angle = Mathf.Atan2(direction.x, direction.y) * Mathf.Rad2Deg;

// since this seems to be a rigidbody I would rather use this
rb.MoveRotation(Quaternion.Slerp(rb.rotation, Quaternion.Euler(0, 0, angle), 0.7f);

// NOTE: Or in case your rb is actually Rigidbody2D then rather simply
rb.MoveRotation(Mathf.Lerp(rb.rotation, angle, 0.7f));

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

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