这款游戏是3D的,但视角是 "正字形 "的,请看下面的插图,以便更清楚地了解视角。
我想把我的玩家的旋转设置为始终面对游戏世界中的鼠标位置,但只让玩家围绕Y旋转轴旋转。
我的伪代码是这样的。
请看。例证
我建议你有两种方法:1)使用射线广播,在角色站立的地方打出你的表面,比如ScreePointToRay。2) 用Camera.WorldToScreenPoint将角色位置转换为屏幕点,然后计算鼠标点和角色点之间的角度。然后你就可以知道它们之间的角度了。
请注意名为LookAt的函数,也许会很方便。
从你的伪代码开始,你可以通过简单地查看API来找到这些函数。
get mouse pos on screen.
Unity已经提供了这个功能。Input.mousePosition
get player pos in world.
一旦你有了一个引用,根据 GameObject
或者直接 Transform
您可以简单地访问其 position
将屏幕上的鼠标位置转换为世界上的鼠标位置。
有多种解决方案,如 Camera.ScreenToWorldPoint
. 然而,在这种情况下,创建一个数学模型会更容易。Plane
再用 Camera.ScreenPointToRay
以便为你的鼠标获取一条射线,并将其传递到 Plane.Raycast
.
确定从鼠标位置到玩家位置的距离。
使用角度来不断调整玩家的旋转以适应鼠标位置。
这些都是不必要的,因为Unity已经为你做了所有这些;)
相反,你可以简单地计算从你的播放器到鼠标射线击中平面的点的矢量方向,抹去鼠标射线与平面之间的差值,就可以得到你所需要的矢量。Y
轴和使用 Quaternion.LookRotation
以便旋转播放器,使其看向同一方向。
因此,它可以看起来像,例如
// drag in your player object here via the Inspector
[SerializeField] private Transform _player;
// If possible already drag your camera in here via the Inspector
[SerilaizeField] private Camera _camera;
private Plane plane;
void Start()
{
// create a mathematical plane where the ground would be
// e.g. laying flat in XZ axis and at Y=0
// if your ground is placed differently you'ld have to adjust this here
plane = new Plane(Vector3.up, Vector3.zero);
// as a fallback use the main camera
if(!_camera) _camera = Camera.main
}
void Update()
{
// Only rotate player while mouse is pressed
// change/remove this according to your needs
if (Input.GetMouse(0))
{
//Create a ray from the Mouse position into the scene
var ray = _camera.ScreenPointToRay(Input.mousePosition);
// Use this ray to Raycast against the mathematical floor plane
// "enter" will be a float holding the distance from the camera
// to the point where the ray hit the plane
if (plane.Raycast(ray, out var enter))
{
//Get the 3D world point where the ray hit the plane
var hitPoint = ray.GetPoint(enter);
// project the player position onto the plane so you get the position
// only in XZ and can directly compare it to the mouse ray hit
// without any difference in the Y axis
var playerPositionOnPlane = plane.ClosestPointOnPlane(_player.position);
// now there are multiple options but you could simply rotate the player so it faces
// the same direction as the one from the playerPositionOnPlane -> hitPoint
_player.rotation = Quaternion.LookRotation(hitPoint-playerPositionOnPlane);
}
}
}