尝试创建进入gungeon类型的武器,但卡住使武器旋转面对鼠标



我正在制作一款类似于《Enter The Gungeon》的游戏,并且我也在一个类似于它们的unity空间中工作。我正在使用unity 3D并制作一款2.5D游戏,以赋予它与gungeon相同的视角。然而,我试图使它,所以武器将面对鼠标和它不工作。我试了很多教程,但都没用。

问题在于,当游戏处于自顶向下视角时,它会将所有其他轴的旋转改变为0,所以我将四边形的X轴旋转为90。根据我的实验,我需要Y轴跟随鼠标。除非有更好的方法去做这件事,我怎么能做到这与我目前的设置?

这是我一直在使用的代码,它有点工作,但它重置了除z以外的所有轴

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MouseFollow : MonoBehaviour
{




private void Start()
{

}

private void Update()
{

var dir = Input.mousePosition - Camera.main.WorldToScreenPoint(transform.position);
var angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
}




}

我能想到的最简单的解决方案是创建一个空对象,并将其作为枪械模型的父对象。这将确保枪(子GameObject)可以保持自己的旋转而不重置它,而父GameObject可以使用你上面描述的方法在y轴上旋转。

如果这不是一个选项,您可以为您想要保留的所有旋转创建另一个四元数,这与鼠标方向无关。然后,对于每一帧,将你生成的方向乘以它来获得你想要的旋转。

transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward) * thePersistingQuaternion

我在尝试完成类似的任务时创建了这个函数。

函数接受2个Vector3点,并返回对象"查找"另一个点所需的四元数。

p1为原点。p2是你想看的点。

对于您的解决方案,您可以使用枪对象的变换作为原点,并使用鼠标位置作为您想要查看的点。


public static Quaternion LookAt(Vector3 p1, Vector3 p2)
{
float angle = 0;
float opp;
float adj;
if (p1.x == p2.x)
{
//Looking down
if (p1.y > p2.y)
{
angle = 0;
}
//Looking up
else
{
angle = 180;
}
}
else if (p1.y == p2.y)
{
//Looking right
if (p1.x < p2.x)
{
angle = 90;
}
//Looking left
else
{
angle = 270;
}
}
else
{
if (p1.x < p2.x)
{
//First quadrant angle +0
if (p1.y > p2.y)
{
angle = 0;
opp = Mathf.Abs(p1.x - p2.x);
adj = Mathf.Abs(p1.y - p2.y);
}
//Second quadrant angle +90
else
{
angle = 90;
adj = Mathf.Abs(p1.x - p2.x);
opp = Mathf.Abs(p1.y - p2.y);
}
}
//if (p1.x > p2.x)
else
{
//Third quadrant angle +180
if (p1.y <= p2.y)
{
angle = 180;
opp = Mathf.Abs(p1.x - p2.x);
adj = Mathf.Abs(p1.y - p2.y);
}
//Forth quadrant angle +270
else
{
angle = 270;
adj = Mathf.Abs(p1.x - p2.x);
opp = Mathf.Abs(p1.y - p2.y);
}
}
float a = Mathf.Atan(opp / adj) * 180f / Mathf.PI;
angle += a;
}
Quaternion rotation = Quaternion.Euler(0, 0, angle);
return rotation;
}

最新更新