无法将类型"float"隐式转换为"UnityEngine.Quaternion"



我正在开发一款2D游戏,但我需要能够朝着鼠标的方向射击,所以我试图将空位的旋转设置为指向鼠标,这样投射物就可以从空位射击,因为我不想让角色旋转,但我在最后一行出现了错误"无法将类型"float"隐式转换为"UnityEngine.Quaternion"我该如何解决这个问题?我不能使用刚体2D,因为空的是有RidgidBody2D和对撞机的播放器的父对象和内部。如果有更好的方法(可能有(,请告诉我。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Point_and_Shoot : MonoBehaviour
{
public Camera cam;
public Rigidbody2D rb; //Ridgidbody of player
public Transform rb2; //Transform of empty (empty is at same position as player but it's parented so I have to take position from player because the position is relative to the parent)
Vector2 mousePos;
void Update()
{
mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
}
void FixedUpdate()
{
Vector2 lookDir = mousePos - rb.position;
float angle = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg - 90f;
rb2.rotation = angle; //<-- The error is here
}
}

四元数表示整个对象的旋转,而不仅仅是角度。尝试直接设置eulerAngles,因为它接受角度作为浮点值(Vector3(。如果你想绕Z轴旋转90°,它看起来像这样:

eulerAngles = new Vector3(0, 0, 90); // Create/set euler angles in degrees.
quaternion.eulerAngles = eulerAngles; // Apply set euler angles to our quaternion
transform.rotation = quaternion; // Apply quaternion to our game object/transform

如果你想创建某种连续(旋转(运动,你应该记住Time.Delta时间作为一个因素。

您的"角度";变量为浮点数据类型。这不能指定给四元数,因为四元数调用4个值(float仅指定1(。或者,你可以这样做:

public Quaternion rb2.rotation;

然后以的形式将角度分配为四元数

这样的东西可以在中工作

float angle = Mathf.Atan2(1, 2) * Mathf.Rad2Deg - 90f;
rb2.rotation = new Quaternion(angle, 0, 0, 0);

您可以使用构造函数Quaternion,而不是将旋转设置为单个值。输入四个值。前三个是x、y和z。在这种情况下不需要第四个此处仅适用类型"四元数">。不能使用Vector3或Vector2。您可以将角度变量移动到y或z位置,因为您可能不想按上面所写的方式旋转。链接

读取类型系统

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/types/

这是一个很好的解释

相关内容

最新更新