Как я могу добавить вращение к своим пулям, когда они выстреливаются?

#c# #unity3d #rotation

Вопрос:

Я давно не использовал ротацию, поэтому не могу вспомнить, как это сделать. Я пытаюсь создать случайную траекторию для своих пуль, и я хочу добавить случайное вращение, но я не знаю, как добавить вращение. Я прокомментировал в скрипте, где должна быть добавлена ротация. Я попытался добавить transform.rotation * Quaternion.Euler(0,rot, 0) , но получил ошибку error CS0019: Operator ' ' cannot be applied to operands of type 'Vector3' and 'Quaternion' . Что я мог бы добавить, чтобы это сработало?

       using System.Collections;
      using System.Collections.Generic;
      using UnityEngine.UI;
      using UnityEngine;
      
      public class Player : MonoBehaviour
      {
          public GameObject bulletPrefab;
      
          public Camera playerCamera;    
      
          private Coroutine hasCourutineRunYet = null;
      
          public int ammo = 300;
          public Text Ammmo;
      
          private float xPos;
          private float zPos;
          private float yPos;
      
          private float rot;
      
          // Update is called once per frame
          void Update()
          {        
              Ammmo.text = "Ammo: "   ammo.ToString();        
              
              if(Input.GetMouseButtonDown(0))
              {
                  if (hasCourutineRunYet == null)
                      hasCourutineRunYet = StartCoroutine(BulletShot());
              }
          }
      
          IEnumerator BulletShot()
          {
              xPos = Random.Range(-0.3f, 0.3f);
              yPos = Random.Range(-0.3f, 0.3f);
              zPos = Random.Range(-0.3f, 0.3f);
              rot = Random.Range(-10.0f, 10.0f);
      
              GameObject bulletObject = Instantiate(bulletPrefab);
              bulletObject.transform.position = playerCamera.transform.position   playerCamera.transform.forward   new Vector3(xPos, yPos, zPos) ; // add rotation here
              bulletObject.transform.forward = playerCamera.transform.forward;
      
              yield return new WaitForSeconds(1.0f);
              hasCourutineRunYet = null;
              ammo--;
          }
      }

 

Ответ №1:

Я бы изучил эту transform.rotation.RotateAround функцию. С помощью этого вы можете вызвать относительное движение вашей пули вперед и по существу вращаться вокруг себя

Код Ниже:

 using UnityEngine;

//Attach this script to a GameObject to rotate around the target position.
public class Example : MonoBehaviour
{
    //Assign a GameObject in the Inspector to rotate around
    public GameObject target;

    void Update()
    {
        // Spin the object around the target at 20 degrees/second.
        transform.RotateAround(target.transform.position, Vector3.up, 20 * Time.deltaTime);
    }
}

 

Вот URL-адрес документации: https://docs.unity3d.com/ScriptReference/Transform.RotateAround.html