简体   繁体   English

统一实例化对象后旋转对象的正确方法

[英]Correct way to rotate object after instancing it in unity

So I'm making a top down shooting game and I want the bullets to align with the direction they are shot at.所以我正在制作一个自上而下的射击游戏,我希望子弹与它们射击的方向对齐。 I'm passing the direction when instancing the bullet(code bellow) and applying it on the Start event but it doesn't rotate.我在实例化子弹(代码波纹管)并将其应用于 Start 事件时传递了方向,但它不旋转。 However it applies when i use it on the Update event indicating that the value is indeed passed but somehow the Start event isn't able to rotate the object.但是,当我在 Update 事件上使用它时它适用,表明该值确实已传递但不知何故 Start 事件无法旋转对象。 I also tried the OnEnable event and same thing, it seems inneficient to set the rotation in every Update event how can i fix it.我也尝试了 OnEnable 事件和同样的事情,在每个更新事件中设置旋转似乎是无效的,我该如何解决它。

{
    [SerializeField] private float speed = 1f;
    public Vector3 direction = Vector3.forward;
    private float distanceTravelled = 0f;

    void Start()
    {
        transform.LookAt(direction);;
    }
    void Update()
    {
        transform.position += speed * Time.deltaTime * direction;
        distanceTravelled += speed * Time.deltaTime;
        if (distanceTravelled > range)
        {
            Destroy(gameObject);
        }
    }
}

I think i fixed it, if theres a better solution please tell me :) I used Invoke fujnction, it seems to delay the rotation enough so it gets properly applied.我想我修好了,如果有更好的解决方案请告诉我:) 我使用了 Invoke 功能,它似乎足够延迟旋转,所以它得到正确应用。

{
    [SerializeField] private float speed = 1f;
    public Vector3 direction = Vector3.forward;
    private float distanceTravelled = 0f;

    void Start()
    {
        Invoke(nameof(SetForwardVector), 0f);
    }
    void Update()
    {
        transform.position += speed * Time.deltaTime * direction;
        distanceTravelled += speed * Time.deltaTime;
        if (distanceTravelled > range)
        {
            Destroy(gameObject);
        }
    }
    void SetForwardVector()
    {
        transform.LookAt(direction);
    }
}

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

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