C# 对象以其自身的旋转实例化,我无法更改
在我的unity项目中,我试图实例化一个当玩家点击时向前移动的球体。 当球体被实例化时,它总是朝着同一个方向移动,无论玩家朝哪个方向。 我试着让它和玩家的方向一致,但没有成功 如何实例化与我的播放器旋转相同的对象 实例化代码:C# 对象以其自身的旋转实例化,我无法更改,c#,unity3d,C#,Unity3d,在我的unity项目中,我试图实例化一个当玩家点击时向前移动的球体。 当球体被实例化时,它总是朝着同一个方向移动,无论玩家朝哪个方向。 我试着让它和玩家的方向一致,但没有成功 如何实例化与我的播放器旋转相同的对象 实例化代码: if (polyWand.activeSelf == true) { Quaternion playerRotation = Quaternion.Euler(player.transform.rotation.x, pla
if (polyWand.activeSelf == true)
{
Quaternion playerRotation = Quaternion.Euler(player.transform.rotation.x, player.transform.rotation.y, player.transform.rotation.z);
Instantiate(fireSpellPrefab, SpellLocation, playerRotation);
}
精神错乱对象的行为:
void Update ()
{
Destroy(this, 5f);
transform.rotation = Player.transform.rotation;
transform.position += Vector3.forward * 9 * Time.deltaTime;
}
代码始终沿Z轴发送对象,因为transform.position不知道对象朝向哪个方向。这是一个与旋转矢量完全不同的矢量。要使某个对象沿相对于对象旋转的方向移动,请尝试:
transform.position += transform.forward * 9 * Time.deltaTime;
我没有尝试过,但每个变换都有自己的前向向量。由于变换同时包含旋转矢量和位置矢量,所以这应该是可行的
但对于类似的情况,通常使用transform.forward来帮助初始定位对象,然后使用Rigidbody.velocity来实际移动对象
编辑:
我也尝试过类似的方法,transform.forward本身将提供投射物的起点和行进方向。我为你树立了一个榜样
public class PlayerControl : MonoBehaviour
{
public float speed;
public float projectileSpeed;
public Transform projectile;
private Transform instantiatedProjectile;
private bool projectileLaunched;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
var rotationAngle = 0f;
if (Input.GetKey(KeyCode.A))
{
rotationAngle = -speed * Time.deltaTime;
transform.Rotate(Vector3.up, rotationAngle);
}
if (Input.GetKey(KeyCode.D))
{
rotationAngle = speed * Time.deltaTime;
transform.Rotate(Vector3.up, rotationAngle);
}
if (Input.GetKeyDown(KeyCode.Space))
{
instantiatedProjectile = Instantiate(projectile, transform.forward, Quaternion.identity);
projectileLaunched = true;
}
if (projectileLaunched)
{
var projPos = instantiatedProjectile.position;
projPos += transform.forward * projectileSpeed;
instantiatedProjectile.position = projPos;
}
}
}
在这个例子中,我所做的只是创建一个立方体作为玩家,创建一个球作为投射物,并将其制作成一个预制件。然后我将此脚本附加到播放器多维数据集。我已经为您编写了一个示例。只需再次查看您的代码,我想我看到了您可能已经完成的操作。Transform.forward必须位于实例化投射物的类中。或者,您可以在投射类中使用transform.position+=Player.transform.forward*9*Time.DeltaTime。